User`s manual
Examples of C MEX-Files
2-27
#define IsNonZero(d) ((d) != 0.0)
#endif
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* Declare variables. */
int elements, j, number_of_dims, cmplx;
int nnz = 0, count = 0;
double *pr, *pi, *pind;
const int *dim_array;
/* Check for proper number of input and output arguments. */
if(nrhs != 1) {
mexErrMsgTxt("One input argument required.");
}
if(nlhs > 1) {
mexErrMsgTxt("Too many output arguments.");
}
/* Check data type of input argument. */
if(!(mxIsDouble(prhs[0]))) {
mexErrMsgTxt("Input array must be of type double.");
}
/* Get the number of elements in the input argument. */
elements = mxGetNumberOfElements(prhs[0]);
/* Get the data. */
pr = (double *)mxGetPr(prhs[0]);
pi = (double *)mxGetPi(prhs[0]);
cmplx = ((pi == NULL) ? 0 : 1);
/* Count the number of non-zero elements to be able to allocate
the correct size for output variable. */
for(j = 0; j < elements; j++) {
if(IsNonZero(pr[j]) || (cmplx && IsNonZero(pi[j]))) {
nnz++;
}
}