【问题标题】:Represent a sparse matrix in C using the CSparse Library使用 CSparse 库在 C 中表示稀疏矩阵
【发布时间】:2014-04-07 08:26:05
【问题描述】:

我不明白如何使用 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结构是这样的

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;

我要问的是如何用我的数据填充我的矩阵以及我必须使用哪种方法来解决它。

谢谢

【问题讨论】:

  • 您的矩阵在实践中有多大?
  • 大矩阵,例如 918*918 我发布的代码只是为了了解如何使用这个库......但我需要使用更大的矩阵

标签: c matrix linear-algebra sparse-matrix


【解决方案1】:

您可以使用cs_load 从文件中读取矩阵。 (每行一个条目,LINE COLUMN DOUBLE,你可以看到这个example

或者使用cs_entry设置矩阵的值:cs_entry (matrix, i, j, 0.42);

您可能希望看到这个full examplethis

更新

数据结构A 不应包含有关b 的任何信息。整个数据结构是A 的稀疏表示。此外,您不应该自己初始化它,而是让cs_spalloc 来完成这项工作。 (例如cs_spalloc (0, 0, 1, 1, 1))。 然后使用 cs_entry 设置值。

对于您要求解的方程的右侧部分 (Ax = b),如果 b 应该是密集的,那么您应该使用一个简单的 C 数组:

简单地说:double b[]={10.0,20.0,30.0};

终于可以拨打cs_lsolve(A, b)了。

【讨论】:

  • 哇,太好了!但是如何设置系数?解决的方法是cs_lsolve?
  • 关于解决部分,你的问题不是很清楚,但我想你想解决类似Ax = b的问题。您可以使用cs_usolve(A, x)。向量b 由指针x 给出,输出由x 给出。 (x 是稠密的)
  • 这就是我要做的尝试,cs_entry (&A, 0, 0, 1.0); cs_entry (&A, 0, 1, 0.0); cs_entry (&A, 0, 2, 2.0); cs_entry (&A, 1, 0, 3.0); cs_entry (&A, 1, 1, 4.0); cs_entry (&A, 1, 2, 0.0); cs_entry (&A, 2, 0, 0.0); cs_entry (&A, 2, 1, 0.0); cs_entry (&A, 2, 2, 5.0);
  • 您想知道如何创建b 向量吗?它是一个简单的 C 数组。或者你想让b 也很稀疏?
  • 我需要解决示例中的问题才能了解 csparse 的工作原理。我已经用我的实际代码在我的问题中发布了更新。它不起作用。但我不明白出了什么问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 2018-01-19
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
  • 2011-10-07
  • 2021-11-18
相关资源
最近更新 更多