필터 지우기
필터 지우기

Help calling a matlab function in a mex function

조회 수: 2 (최근 30일)
htrh5
htrh5 2015년 7월 4일
편집: htrh5 2015년 7월 4일
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++)
pr[i]=i*(4*3.14159/max);
}
/* 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;
rhs[0]=0;
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 */
mxDestroyArray(rhs[0]);
mxDestroyArray(lhs[0]);
mxDestroyArray(inplot[0]);
mxDestroyArray(inplot[1]);
return;
}
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?

채택된 답변

htrh5
htrh5 2015년 7월 4일
편집: htrh5 2015년 7월 4일
forgot about pointer stuff, oups. This fixed it:
rhs[0]=mxCreateDoubleMatrix(1, 1, mxREAL);
double* pw=mxGetPr(rhs[0]);
pw[0]=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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by