我不明白如何使用 CSparese 库轻松地在 C 中表示稀疏矩阵。
这就是我想要的
| 6.0 0.0 2.0 |
A = | 3.0 8.0 0.0 |
| 6.0 0.0 1.0 |
with
| 40.0 |
b = | 50.0 |
| 30.0 |
csparse的cs Struct是这样的
typedef struct cs_sparse /* matrix in compressed-column or triplet form */
{
csi nzmax ; /* maximum number of entries */
csi m ; /* number of rows */
csi n ; /* number of columns */
csi *p ; /* column pointers (size n+1) or col indices (size nzmax) */
csi *i ; /* row indices, size nzmax */
double *x ; /* numerical values, size nzmax */
csi nz ; /* # of entries in triplet matrix, -1 for compressed-col */
} cs ;
这就是我所做的
int main(int argc, const char * argv[])
{
cs A;
int N = 3;
double b[]={1,2,3};
double data[]={1,1,1};
csi columnIndices[]={0,1,2};
csi rowIndices[]={0,1,2};
A.nzmax =3;
A.m = N;
A.n = N;
A.p = &columnIndices[0];
A.i = &rowIndices[0];
A.x = &data[0];
A.nz = 3;
cs *B = cs_compress(&A);
int status = cs_cholsol(0,B,&b[0]);
printf("status=%d",status); // status always returns 0, which means error
return 0;
我问的是如何用我的数据填充我的矩阵以及我必须使用哪种方法来解决它。
谢谢
最佳答案
您可以使用cs_load
从文件中读取矩阵。 (每行一个条目,LINE COLUMN DOUBLE
,您可以看到这个 example )
或者使用cs_entry
设置矩阵的值:cs_entry(matrix, i, j, 0.42);
您可能想查看此 full example ,和this
更新
数据结构A
不应包含有关b
的任何信息。整个数据结构是A
的稀疏表示。此外,您不应该自己初始化它,而应该让 cs_spalloc
来完成这项工作。 (例如 cs_spalloc (0, 0, 1, 1, 1)
)。
然后使用cs_entry设置值。
对于您想要求解的方程的右侧部分 (Ax = b
),那么如果 b
应该是稠密的,则您应该使用 a简单的 C 数组:
简单地说:double b[]={10.0,20.0,30.0};
最后你可以调用cs_lsolve(A, b)
。
关于c - 使用 CSparse 库在 C 中表示稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22907166/