Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: populating a sparse matrix in mex
Replies: 1   Last Post: Nov 18, 2013 1:44 AM

 Messages: [ Previous | Next ]
 James Tursa Posts: 2,326 Registered: 8/5/09
Re: populating a sparse matrix in mex
Posted: Nov 18, 2013 1:44 AM

"Alexandre" wrote in message <l68f9v\$5sc\$1@newscl01ah.mathworks.com>...
> 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

The sparse function in MATLAB has built-in sorting capabilities, which is why it doesn't require you to supply row & column index data in pre-sorted order. Your options are to include sorting capabilities in your mex routine, or use call-backs into MATLAB via mexCallMATLAB to get your data sorted PRIOR to handing the sparse array back to MATLAB.

James Tursa

Date Subject Author
11/16/13 Alexandre
11/18/13 James Tursa