Date: Nov 16, 2013 1:59 PM
Author: Alexandre
Subject: populating a sparse matrix in mex

Hi everyone

I am having difficulties with populating sparse matrices. Here is my code:


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

double *mxRES = NULL ; // output, i.e. first left hand side pointer
mwIndex *ir = NULL ;
mwIndex *jc = NULL ;
mwIndex entry_counter = 0 ;

[...]

// create lmax x kmax sparse matrix
plhs[0] = mxCreateSparse(lmax,kmax,Nelts, mxREAL) ;

mxRES = mxGetPr(plhs[0]) ;
ir = mxGetIr(plhs[0]) ;
jc = mxGetJc(plhs[0]) ;

for (k=0 ; k<kmax ; k++){

jc[(mwIndex)(k)] = entry_counter ;

for (l = 0 ; l<lmax; l++){


lll = some_function( l,k ) ;

// 'some_function' is a function with integer output between 0 and lmax-1

mxRES[entry_counter] = some_value ;
ir[entry_counter] = (mwIndex)(lll) ;
entry_counter++ ;
}
}

jc[ (mwIndex)(kmax) ] = entry_counter ;

////////////////////////////////////////////////////////////////////


my problem is that 'some_function( l )' is non-increasing with respect to l, i.e. some_function( l,k ) is not always greater than some_function( l' ,k) when l>l'. Therefore, for a given column k, when entry_counter is incremented, the row index is not always increasing. This results in some funny results, like if the output mxRES is a matrix X in matlab, then sometime we have [H']' =/= H.

I cannot change 'some_function( l,k )' to make it increasing w.r.t l. Is there any approach to tackle this problem? There must be one since the 'sparse' function in matlab does not require indices to be increasing

Thank you very much