Array int on mex file output

I am trying to create a mex function whose record is an integer and whose output is an array of integers. So the function looks like this: int * myFunction (unsigned int N). In mexFunction, I declare an * variab variable of type int, and then

N = mxGetScalar(prhs[0]); /* assign a pointer to the output */ siz= 2*ceil(log(1.0*N)/log(2.0)-0.5)+1; plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL); vari = (int*) mxGetPr(plhs[0]); */ /* Call the subroutine. */ vari = myFunction(N); mexPrintf("The first value is %d\n", vari[0]); 

Thing the first value is correct (and the others were checked and were correct), but when I call the mxFunction (16) routine, I get only 0 as the output. I think this is because my output is an int array, but I do not know how to solve the problem. Any hint? Greetings.

+4
source share
1 answer

Matlab has double values ​​by default. You can easily use them in your mex function, as in the following example based on your code snippet. I made myFunction, which performs a demo algorithm. Instead of returning a data type, I make it a void function and pass it a pointer to the output so that it can fill it.,.

 /*************************************************************************/ /* Header(s) */ /*************************************************************************/ #include "mex.h" #include "math.h" /*************************************************************************/ /*the fabled myFunction */ /*************************************************************************/ void myFunction(unsigned int N, unsigned int siz, double* output) { int sign = 1; for(int ii=0; ii<siz; ++ii) { output[ii] = (double)(ii * sign + N); sign *= -1; } } /*************************************************************************/ /* Gateway function and error checking */ /*************************************************************************/ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* variable declarations */ unsigned int siz; double N; /* check the number of input and output parameters */ if(nrhs!=1) mexErrMsgTxt("One input arg expected"); if(nlhs > 1) mexErrMsgTxt("Too many outputs"); N = mxGetScalar(prhs[0]); /* assign a pointer to the output */ siz= 2*ceil(log(1.0*N)/log(2.0)-0.5)+1; plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL); myFunction(N, siz, mxGetPr( plhs[0]) ); } 
+3
source

Source: https://habr.com/ru/post/1401476/


All Articles