3

I want to pass a sparse matrix to a shared library from MATLAB, do some operation there (written in C), and then return it.

I can pass a dense matrix and use, pretty easy. But, I have no idea how to pass a sparse matrix to a shared library from MATLAB. What I've found are all concerned about MEX.

It is appreciated if give some information about sparse matrix format in MATLAB and the conversion in C.

Thanks in advance.

Amro
  • 123,847
  • 25
  • 243
  • 454
Pouya
  • 1,871
  • 3
  • 20
  • 25

1 Answers1

2

Internally MATLAB stores sparse matrices using Compressed sparse column (CSC) format. Once you understand the format, you could then pass a sparse matrix to external code by getting the arrays pr, pi, ir, and jc (using the MEX-functions mxGetPr, mxGetPi, mxGetIr, mxGetJc respectively).

  • pr (and pi if the matrix is complex) is a double-precision array of length nzmax containing the nonzero values of the matrix.

  • ir points to an integer array also of length nzmax containing the row indices of the corresponding elements in pr and pi.

  • jc points to an integer array of length n+1, where n is the number of columns in the sparse matrix. The jc array contains column index information. If the j-th column of the sparse matrix has any nonzero elements, jc[j] is the index in ir and pr (and pi if it exists) of the first nonzero element in the j-th column, and jc[j+1] - 1 is the index of the last nonzero element in that column. For the j-th column of the sparse matrix, jc[j] is the total number of nonzero elements in all preceding columns. The last element of the jc array, jc[n], is equal to nnz, the number of nonzero elements in the entire sparse matrix.

Amro
  • 123,847
  • 25
  • 243
  • 454