2017-02-27 36 views
0

我已经有了我的稀疏矩阵数据CSR format,即:我已经有非零值的数据(形式为double[]),非零值的行和列索引(形式为int[])。如何为CSR格式设置SparseMatrix.valuePtr(),SparseMatrix.outerIndexPtr()和SparseMatrix.innerIndexPtr()?

我的问题是,我如何将它们直接分配给特征库中的稀疏矩阵?我知道,在稀疏矩阵相关领域是valuePtrouterIndexPtrinnerIndexPtr,但我不能直接设置指针为每如下:

//the relevant SpMat fields (valuePtr,outerIndexPtr,innerIndexPtr) are not able to set 

static SpMat CSRFormat2(double* nonZeroPtr, int* rowIndex, 
int* colIndex, int totDOF, int nonZeroCount) 
{ 
    SpMat sparseMatrix = SpMat(totDOF,totDOF); 

    double *nonZ=sparseMatrix.valuePtr(); 
    nonZ=nonZeroPtr; 

    int *outerIndex = sparseMatrix.outerIndexPtr(); 
    outerIndex=rowIndex; 

    int *innerIndex = sparseMatrix.innerIndexPtr(); 
    innerIndex = colIndex; 

    sparseMatrix.reserve(nonZeroCount); 

    return sparseMatrix; 

} 

我不想遍历非零值和集再一次。我认为这样做效率不高。

如何设置SparseMatrix.valuePtr(),SparseMatrix.outerIndexPtr()SparseMatrix.innerIndexPtr(),如果可以的话?

+0

您正在寻找[地图<稀疏矩阵>](https://eigen.tuxfamily.org/dox-devel/classEigen_1_1Map_3_01SparseMatrixType_01_4。 html) – ggael

+0

@ggael,您想将您的评论扩展为正确的答案吗?这样它可以被投票(上) – Graviton

回答

0

由于the comment from ggael,我这是怎么解决这个问题:

 ///CSR format: nonZeroArray, rowIndex, colIndex 
     SparseMatrix<double, Eigen::RowMajor> ConstructSparseMatrix(int rowCount, int colCount, int nonZeroCount, double *nonZeroArray, int *rowIndex, int *colIndex) 
     { 
      Map<SparseMatrix<double, Eigen::RowMajor>> spMap(rowCount, colCount, nonZeroCount, rowIndex, colIndex, nonZeroArray, 0); 
      SparseMatrix<double, Eigen::RowMajor> matrix= spMap.eval(); 
      matrix.reserve(nonZeroCount); 
      return matrix; 
     } 
1

这是一个我没有真正测试(最近)的黑客攻击。然而,这确实复制值:

SparseMatrix<double, whatever, indexType> m; 
m.resize(rows, cols); 
m.makeCompressed(); 
m.resizeNonZeros(nnz); 

memcpy((void*)(m.valuePtr()), (void*)(valueSrc), sizeof(double) * nnz); 
memcpy((void*)(m.outerIndexPtr()), (void*)(outerIndexPtrSrc), sizeof(indexType) * outSz); 
memcpy((void*)(m.innerIndexPtr()), (void*)(innerIndexPtrSrc), sizeof(indexType) * nnz); 

m.finalize(); 

如果您不想复制的记忆,那么就分配指针(sparseMatrix.valuePtr() = nonZeroPtr;)后会产生问题,因为矩阵认为它拥有的内存,并会删除它破坏。您应该改为使用std::swap

最后一个注释,Eigen::SparseMatrix的索引类型可能不是int,所以您可能想在复制/交换之前处理该问题。