gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:52:23 25 4
gpt4 key购买 nike

我的稀疏矩阵数据已经在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com