/* validIdx_mex.c
*
* B = validIdx_mex(n,A)
*
* Creates a vector of indexes 1:n but excluding those indexes in A.
*
* Programmer: James Tursa
*/
/* Includes ----------------------------------------------------------- */
#include "mex.h"
/* Gateway ------------------------------------------------------------ */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mwSize i, j, n, m;
double *Bpr, *Apr, *bpr;
/* Argument checks */
if( nrhs != 2 || !mxIsNumeric(prhs[0]) || !mxIsDouble(prhs[1]) ||
mxGetNumberOfElements(prhs[0]) != 1 || mxIsSparse(prhs[1]) ||
mxIsComplex(prhs[0]) || mxIsComplex(prhs[1]) ) {
mexErrMsgTxt("Invalid inputs");
}
n = mxGetScalar(prhs[0]);
if( n <= 0 ) {
mexErrMsgTxt("Invalid 1st argument");
}
m = mxGetNumberOfElements(prhs[1]);
Apr = mxGetPr(prhs[1]);
/* Create the output */
plhs[0] = mxCreateDoubleMatrix( 1, n, mxREAL );
Bpr = mxGetPr(plhs[0]);
/* Fill the output with default indexing */
bpr = Bpr;
for( i=1; i<=n; i++ ) {
*bpr++ = i;
}
/* Put 0's in the ignore spots */
for( i=0; i<m; i++ ) {
j = *Apr;
if( j != *Apr || j < 1 ) {
mexErrMsgTxt("Invalid 2nd argument value");
} else if( j <= n ) {
Bpr[j-1] = 0;
}
Apr++;
}
/* Shift all the non-zero indexes to the front */
bpr = Bpr;
j = 0;
for( i=0; i<n; i++ ) {
if( *bpr ) {
*Bpr++ = *bpr;
j++;
}
bpr++;
}
/* Set the new size based on the number of actual non-zeros */
mxSetN(plhs[0],j);
}
Best Answer