MATLAB: Printing Sparse Matrix in mex function in CCS format

ccs formatcompressed column storagemexprinftprint sparse matricessparse matrix

Hi,
I am relatively new user of mex and matlab.I have to do some operations on sparse matrices,which also includes printing them in CCS format.Here is the code that I have written.
#include "mex.h"
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
double *A;
int *jc,*ir;
int m,n,size;
int i;
A = mxGetPr(prhs[0]);
m = mxGetM(prhs[0]);
n = mxGetN(prhs[0]);
jc = (int*) mxGetJc(prhs[0]);
ir = (int*) mxGetIr(prhs[0]);
size = mxGetNzmax(prhs[0]);
plhs[0] = mxCreateSparse(m,n,size,mxREAL);
mexPrintf("JC: ");
for(i = 0; i < m;i++)
{
mexPrintf("%d ",jc[i]);
}
mexPrintf("\n");
mexPrintf("IR:");
for(i = 0;i < size;i++)
{
mexPrintf("%d ",ir[i]);
}
mexPrintf("\n");
mexPrintf("Values:");
for(i = 0;i < size;i++)
{
mexPrintf("%g ",A[i]);
}
mexPrintf("\n");
}
But the output that I am getting is like this.
>> a = sprand(4,4,0.3)
a =
(1,1) 0.4898
(3,2) 0.6463
(4,2) 0.7094
(2,4) 0.4456
(4,4) 0.7547
>> com(a)
JC: 0 0 1 0
IR:0 0 2 0 3
Values:0.489764 0.646313 0.709365 0.445586 0.754687
ans =
All zero sparse: 4-by-4
>> full(a)
ans =
0.4898 0 0 0
0 0 0 0.4456
0 0.6463 0 0
0 0.7094 0 0.7547
Is this correct? since I dont see the row indices getting printed correctly.Further, is there any in built function to print the sparse matrices in CCS format?
Kindly reply.
Cheers.

Best Answer

I'm not sure what your real question is. Do you just want to print a sparse matrix from within a mex function? If so, you can use this function:
void spprint(const mxArray *mx)
{
mwSize n, nrow;
mwIndex *ir, *jc;
mwIndex j, x, y;
double *pr;
if( !mxIsSparse(mx) ) return;
n = mxGetN(mx);
pr = mxGetPr(mx);
ir = mxGetIr(mx);
jc = mxGetJc(mx);
for( y=0; y<n; y++ ) {
nrow = jc[y+1] - jc[y];
for( x=0; x<nrow; x++ ) {
mexPrintf(" (%d,%d) %g\n",(*ir++)+1,y+1,*pr++);
}
}
}
Incidentally, you should never recast function pointer return values like this:
jc = (int*) mxGetJc(prhs[0]);
ir = (int*) mxGetIr(prhs[0]);
This will not work if mwIndex is not an int. Best to just declare jc and ir as mwIndex pointers (not int pointers) and then don't cast the result of the functions and you will be fine.