简体   繁体   中英

Mex sparse matrix

I created a sparse matrix in MEX using mxCreateSparse .

mxArray *W;
W=mxCreateSparse(n*n,n*n,xsize,mxREAL);
double *wpoint;
wpoint=mxGetPr(W);
for(p=0;p<xsize;p++)
 {
     Wpoint[(returnindex1(xi[p][0],xi[p][1])-1)*n*n + (returnindex1(xj[p][0],xj[p][1]))]=   exp(-df[p]/(SIGMAI*SIGMAI)) * exp(-dx[p]/(SIGMAJ*SIGMAJ));
 }

the maximum value which comes from (returnindex1(xi[p][0],xi[p][1])-1)*n*n + (returnindex1(xj[p][0],xj[p][1])) is n*n*n*n and I have created the sparse matrix of dimension (n*n)X(n*n)

When I display the whole matrix, some of the zero elements come as junk. Also for large values of n , segmentation fault occurs at wpoint .

The pr array holds xsize elements and you accessing the array with out of bounds indices. Hence the seg violation.

I think your fundamental problem is that you have not fully grasped how sparse matrices are stored in MATLAB. I'm not an expert on the MATLAB implementation details but my recollection is that it uses compressed column storage.

In essence there are 3 arrays as follows:

  • double pr[NZMAX] which contains the NZMAX non-zero values.
  • int ir[NZMAX] which contains the row number of each value in pr .
  • int jc[m] which indexes into pr and ir identifying the first item in each of the m columns.

That's the executive summary, but I recommend that you read up on the details more carefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM