MATLAB: Can I pass a pointer to a matrix created in MATLAB to C via a MEX file and change the data in it

change values in an array passed from matlab to mex codeMATLABmexpointers

In MATLAB I would like to create an 1xN array of zeros, pass it to a C routine as an input argument, have the C routine update the (type double) values in the array (matrix in MATLAB). I would like to do this instead of having the MEX routine return a matrix (as is done in the example arrayProduct.c)
Is this possible, and if so, does anyone have any examples they would be willing to share?

Best Answer

Make the second to last line in step 2 this and it will work:
workOnExistingMatrix(mxGetPr(prhs[0]));
Here's the corrected MEX file:
//This is the MEX file (written in C)
#include "mex.h"
void workOnExistingMatrix(double* aMatrixCreatedInMatlab) {
aMatrixCreatedInMatlab[0] = 0.1234;
}
//The gateway function
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
//This works =)
workOnExistingMatrix(mxGetPr(prhs[0]));
}