User`s manual
2 Creating C Language MEX-Files
2-28
/* Get the number of dimensions in the input argument.
Allocate the space for the return argument */
number_of_dims = mxGetNumberOfDimensions(prhs[0]);
plhs[0] = mxCreateDoubleMatrix(nnz, number_of_dims, mxREAL);
pind = mxGetPr(plhs[0]);
/* Get the number of dimensions in the input argument. */
dim_array = mxGetDimensions(prhs[0]);
/* Fill in the indices to return to MATLAB. This loops through
* the elements and checks for non-zero values. If it finds a
* non-zero value, it then calculates the corresponding MATLAB
* indices and assigns them into the output array. The 1 is added
* to the calculated index because MATLAB is 1-based and C is
* 0-based. */
for(j = 0; j < elements; j++) {
if(IsNonZero(pr[j]) || (cmplx && IsNonZero(pi[j]))) {
int temp = j;
int k;
for(k = 0; k < number_of_dims; k++) {
pind[nnz*k+count] = ((temp % (dim_array[k])) + 1);
temp /= dim_array[k];
}
count++;
}
}
}
Entering a sample matrix at the MATLAB prompt gives
matrix = [ 3 0 9 0; 0 8 2 4; 0 9 2 4; 3 0 9 3; 9 9 2 0]
matrix =
3 0 9 0
0 8 2 4
0 9 2 4
3 0 9 3
9 9 2 0