MATLAB: Help calling a matlab function in a mex function

MATLABMATLAB C/C++ Math Librarymex

EDIT: See my answer below for clarification.
I want to modify sincall example to make it display besselj(0,x)
#include "matrix.h"
#include <string>
#include "mex.h"
#define MAX 1000
/* subroutine for filling up data */
void fill( double *pr, mwSize *pm, mwSize *pn, mwSize max )
mwSize i;
/* you can fill up to max elements, so (*pr)<=max */
*pm = max/2;
*pn = 1;
for (i=0; i < (*pm); i++)
/* gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
mwSize m, n, max=MAX;
mxArray *rhs[2], *lhs[1];
mxArray *inplot[2]; /* input to plot function */
// (void) nlhs; (void) plhs; /* unused parameters */
// (void) nrhs; (void) prhs;
mxSetM(rhs[0], 1);
mxSetN(rhs[0], 1);
rhs[1] = mxCreateDoubleMatrix(max, 1, mxREAL);
/* pass the pointers and let fill() fill up data */
fill(mxGetPr(rhs[1]), &m, &n, MAX);
mxSetM(rhs[1], m);
mxSetN(rhs[1], n);
inplot[0] = mxDuplicateArray(rhs[1]);
/* get the sin wave */
std::string func=mxArrayToString(prhs[0]);
mexCallMATLAB(1, lhs, 2, rhs, func.c_str());
inplot[1] = mxDuplicateArray(lhs[0]);
/* plot(rhs, sin(rhs)) */
mexCallMATLAB(0, NULL, 2, inplot, "plot");
/* cleanup allocated memory */
This makes matlab crash due to segmentation fault.
I would also like to learn why we set max to 1000 then divide it by 2. We first create an array of 1000 doubles, and then ignore the last 500? Is the last 500 also freed when we destroy array?

Best Answer

  • forgot about pointer stuff, oups. This fixed it:
    rhs[0]=mxCreateDoubleMatrix(1, 1, mxREAL);
    double* pw=mxGetPr(rhs[0]);
    mxSetM(rhs[0], 1);
    mxSetN(rhs[0], 1);
    clearly I can do better than this. What would be the smart way of handling this?
    So the remaining questions:
    -How can I do this without such a roundabout way
    -How can I do this with int rather than double (because I fear this might be giving me besselj(1E-15,x) )
    -Why does the example use max/2