Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

c++ - How to set SparseMatrix.valuePtr(), SparseMatrix.outerIndexPtr() and SparseMatrix.innerIndexPtr() for CSR Format?

I already have my sparse matrix data in CSR format, ie: I already have data for non zero values ( in the form of double[]), the row and the column index ( both in the form of int[]) of the non zero values.

My problem is, how can I assign them directly to Sparse Matrix in eigen library? I know that the relevant fields in Sparse Matrix are valuePtr, outerIndexPtr and innerIndexPtr, but I can't set the pointer directly as per below:

//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;

}

I don't want to iterate over the non zero values and set everything again. That would be inefficient, I think.

How to set SparseMatrix.valuePtr(), SparseMatrix.outerIndexPtr() and SparseMatrix.innerIndexPtr(), if this is possible at all?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a hack that I haven't really tested (recently). It does copy the values, however:

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();

If you would rather not copy the memory, then just assigning the pointers (sparseMatrix.valuePtr() = nonZeroPtr;) will cause problems later, as the matrix thinks it owns the memory and will delete it on destruction. You should probably use std::swap instead.

One last note, the index type of the Eigen::SparseMatrix may not be int, so you may want to deal with that before just copying/swapping.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...