Represent a sparse matrix in C using the CSparse Library

巧了我就是萌 提交于 2019-12-25 18:37:35

问题


I can't understand how can easily represent a sparse matrix in C using the CSparese Library.

That's what I want

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

The cs Struct of the csparse is this

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 ;

That's what I do

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;

What I ask, is how can I populate my matrix with my data and which method I must use to solve it.

Thanks


回答1:


You can either use cs_load which read a matrix from a file. (one entry per line, LINE COLUMN DOUBLE, you can see this example)

Or use cs_entry to set a value of the matrix : cs_entry (matrix, i, j, 0.42);

You might want to see this full example, and this

Update

The data structure A should not contain any information about b. The whole data structure is a sparse representation of A. Moreover, you should not initialize it yourself, but let cs_spalloc do the work. (by example cs_spalloc (0, 0, 1, 1, 1)). And then use cs_entry to set the values.

For the right-hand part of the equation you want to solve (Ax = b), then if b is supposed to be dense, the you should use a simple C array :

Simply : double b[]={10.0,20.0,30.0};

Finally you can call cs_lsolve(A, b).



来源:https://stackoverflow.com/questions/22907166/represent-a-sparse-matrix-in-c-using-the-csparse-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!