MATLAB: How to input and output variable in mex function

mex-function

I want to input an array into a mex function, modify the array, and then output the array without changing the variable name. My attempts to do this have failed. The code runs if I remove the lines:
b = mxGetPr(plhs[1]);
d = mxGetPr(plhs[2]);
but I want to return the values of b and d… I have also tried
plhs[1] = b;
plhs[2] = d;
Also, it is not acceptable to copy the array into another variable which can then be output.
Here is my failing mex function:
#include "mex.h" /*The mex library*/
#include <math.h>
#include <stdlib.h>
void runfunc(double *a, double *b, double *c, double *d, double *x, long ynum)
{
long i;
double w;
for (i = 1; i<ynum; i++)
{
w = a[i]/b[i-1];
b[i] = b[i]-w*c[i-1];
d[i] = d[i]-w*d[i-1];
}
x[ynum-1] = d[ynum-1]/b[ynum-1];
for (i = ynum-2; i!=-1; i--)
{
x[i] = (d[i]-c[i]*x[i+1])/b[i];
}
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
/* DECLARATIONS*/
double *a, *b, *c, *d, *x;
long ynum;
/* INPUTS */
a = mxGetPr(prhs[0]);
b = mxGetPr(prhs[1]);
c = mxGetPr(prhs[2]);
d = mxGetPr(prhs[3]);
ynum = mxGetScalar(prhs[4]);
/* OUTPUTS */
plhs[0] = mxCreateDoubleMatrix(ynum,1,mxREAL);
x = mxGetPr(plhs[0]);
b = mxGetPr(plhs[1]);
d = mxGetPr(plhs[2]);
/* CALL ROUTINE */
runfunc(a,b,c,d,x,ynum);
}

Best Answer

Some issues:
b = mxGetPr(plhs[1]);
d = mxGetPr(plhs[2]);
The above lines crash MATLAB when you try to use b and d downstream because plhs[1] and plhs[2] haven't been created. The plhs variables are output variables that you the programmer need to create before you access them. So, create them first. E.g.,
if( nlhs < 3 ) {
mexErrMsgTxt("Need to specify three output variables");
}
plhs[0] = mxCreateDoubleMatrix(ynum,1,mxREAL);
plhs[1] = mxDuplicateArray(prhs[1]);
plhs[2] = mxDuplicateArray(prhs[3]);
x = mxGetPr(plhs[0]);
b = mxGetPr(plhs[1]);
d = mxGetPr(plhs[2]);
Then of course you don't need these earlier lines at all:
b = mxGetPr(prhs[1]);
:
d = mxGetPr(prhs[3]);
And, to make your mex routine more robust, you should be checking the number and class and size of all of your inputs before using them downstream in your code.
Related Question