How to create a 2d sparse matrix in a MEX-file written in C. After creating the matrix how to access the elements individually like in C , say mat[i][j]?
I tired using mxCreateNumericArray function but I wasn’t able to access the elements and also make it as a sparse matrix.
Please help
See this page on mxCreateSparse. Then you’ll want to look at mxSetPr, mxSetIr and mxSetJc and the corresponding “get” versions.
Here’s an example of how to allocate a sparse matrix. I realize this is an old link, but to the best of my knowledge, it hasn’t changed.
Basically, how it works is that the
irdata contains the row indices. Thejrdata contains a list of indices into theirarray. For instance, in the link on how to allocate a sparse matrix, the code:the array
static_jc_datatells you that indicesstatic_jc_data[c]throughstatic_jc_data[c+1]-1ofstatic_pr_dataandstatic_ir_datacorrespond to the columncof the matrix. Within that range (static_jc_data[c]tostatic_jc_data[c+1]-1) the entries ofstatic_pr_datagives you the values in the matrix andstatic_ir_datagives you the correct rows.For example, the matrix here would be:
To answer your questions about how to access elements individually, you have to search for whether the
i,jth element exists and if it does return it, otherwise return 0. To do this, you’d search fromstatic_ir_data[static_jc_data[j]]throughstatic_ir_data[static_jc_data[j+1]-1]to see whether youriexists. If it does, then the corresponding entry instatic_pr_datawill contain your entry. If it doesn’t, then return 0.However, typically with sparse matrix usage, if you’re doing a lot of searching through the matrix to see if a certain element exists, you may want to think about how you’re using it. Typically, it’s much better to perform whatever operation you’re doing by only going through the non-zero elements once instead of searching for each
i,jth entry.Oh, and one last thing. Keep in mind that in the MEX code, all your indices are 0 based, but they are 1 based in MATLAB. That should add to the fun.