c++ - 如何为CSR格式设置SparseMatrix.valuePtr()、SparseMatrix.outerIndexPtr()和SparseMatrix.innerIndexPtr()?

标签 c++ eigen

我的稀疏矩阵数据已经在 CSR format 中了,即:我已经有非零值的数据(以 double[] 的形式),行和列索引(均以 int[] 的形式) 的非零值。

我的问题是,如何将它们直接分配给特征库中的稀疏矩阵?我知道稀疏矩阵中的相关字段是 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(),如果可以的话全部?

最佳答案

这是我(最近)没有真正测试过的技巧。但是,它确实会复制值:

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,因此您可能希望在复制/交换之前处理它。

关于c++ - 如何为CSR格式设置SparseMatrix.valuePtr()、SparseMatrix.outerIndexPtr()和SparseMatrix.innerIndexPtr()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42481785/

相关文章:

c++ - GetFieldValue 时间变量错误

c++ - 在 header 中定义全局数组的模板技巧

c++ - 在 Visual C++ 2010 中安装 Eigen 库

c++ - 命名空间 ‘Eigen’ 中的 EigenvalueType’ 未命名类型

c++ - c++ 中的薄 QR 分解

c++ - 从函数中通过引用返回 Eigen::VectorXd

c++ - 通过 Function Frustrations c++ 传递对象数组

c++ - 使用 cerr 修复的链表段错误

c++ - 如何对整数数组实现归并排序?

c++ - 访问 eigen3 中的特征值