Skip to content

Instantly share code, notes, and snippets.

@ferryzhou
Created March 19, 2013 21:10
Show Gist options
  • Save ferryzhou/5200166 to your computer and use it in GitHub Desktop.
Save ferryzhou/5200166 to your computer and use it in GitHub Desktop.
show sparse matrix in mex file
#include "mex.h"
// undef needed for LCC compiler
#undef EXTERN_C
// mex mex_show_sparse.cpp -O -largeArrayDims
// a = sparse(rand(10)<0.1)
// mex_show_sparse(a);
// b = a .* rand(10)
// mex_show_sparse(b);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
if(nrhs < 1) { mexErrMsgTxt("no input"); }
if(!mxIsSparse(prhs[0])) { mexErrMsgTxt("input array is not sparse"); }
const mxArray* mxSparse = prhs[0];
size_t m = mxGetM(mxSparse);
size_t n = mxGetN(mxSparse);
double* sr = NULL;
bool* bsr = NULL;
if(mxIsLogical(mxSparse)) { bsr = mxGetLogicals(mxSparse); }
else { sr = mxGetPr(mxSparse); }
mwIndex* irs = mxGetIr(mxSparse);
mwIndex* jcs = mxGetJc(mxSparse);
mwSize nzmax = mxGetNzmax(mxSparse);
mexPrintf("%d x %d sparse matrix has %d values\n", m, n, nzmax);
for (int i = 0; i < n; i++) {
int c = jcs[i+1] - jcs[i];
if (c > 0) {
for (int j = 0; j < c; j++) {
int k = jcs[i] + j;
if (mxIsLogical(mxSparse)){ mexPrintf("(%d,%d): %d\n", irs[k]+1, i+1, bsr[k]); }
else { mexPrintf("(%d,%d): %f\n", irs[k]+1, i+1, sr[k]); }
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment