필터 지우기
필터 지우기

Sparse matrices: find indices of non-zero elements in C code

조회 수: 5 (최근 30일)
Szabolcs
Szabolcs 2013년 2월 1일
I am using the MATLAB Engine interface, and I need to be able to handle sparse matrices.
Starting with an mxArray pointer which turns out to be a sparse matrix, is there an easy way to find the indices and values of non-zero matrix elements---all in C code without calling back to MATLAB?
What I have easy access to is the IR and JC arrays. Are there any functions provided to compute from these the index and value lists?

채택된 답변

James Tursa
James Tursa 2013년 2월 1일
Here is a simple mex routine that mimics the display functionality for sparse matrices (prints only the non-zero values). You should be able to easily extract the indexing code you need from this. The code prints out indexes in 1-based indexing for display purposes, but if you need 0-based indexing an easy -1 adjustment can be made to the code.
#include "mex.h"
void spprint(const mxArray *mx);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if( nrhs ) spprint(prhs[0]);
}
void spprint(const mxArray *mx)
{
mwSize n, nrow;
mwIndex *ir, *jc;
mwIndex j, x, y;
double *pr;
if( !(mx && mxIsSparse(mx) && mxIsDouble(mx)) ) return;
n = mxGetN(mx);
pr = mxGetData(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++);
}
}
}

추가 답변 (1개)

Jan
Jan 2013년 2월 1일

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by