How to read back (and use) a matrix from a matlab function called from a mex file?
Show older comments
I want to read back a matrix from a matlab function called from a mex file and I have been getting a segmentation violation when I try to run it. (At least my assumption is that it is related to how I am reading the matrix; I'm not exactly sure)
Here is an example representing what I am trying to do: (apologies if I include unnecessary detail, I am a novice mex user)
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]){
int ncols=210;
int mrows=210;
int i,j,
double ** a;
double ** b; // matrix to hold matlab output
mxArray * histforce_ips[1];
mxArray * histforce_ops[1];
// allocate memory:
a=(double**)malloc(mrows*sizeof(double *));
b=(double**)malloc(mrows*sizeof(double *));
for(i=0;i<mrows;i++){
a[i]=(double*)calloc(ncols,sizeof(double));
b[i]=(double*)calloc(ncols,sizeof(double));
}
// put something into a:
// ...
// pass a to matlab function
for(i=0;i<ncols;i++){
for(j=0;j<mrows;j++){
(mxGetPr(histforce_ips[0]))[i*mrows+j]=a[j][i];
}
}
// call function:
mexCallMATLAB(1,histforce_ops,1,histforce_ips,"calchistforce");
// extract data
for(i=0;i<ncols;i++){
for(j=0;j<mrows;j++){
b[j][i]=(mxGetPr(histforce_ops[0]))[i*mrows+j];
}
}
// free memory
for(i=0;i<mrows;i++){
free(a[i]);
free(b[i]);
}
free(a); free(b);
}
Thank you for your help.
N
Accepted Answer
More Answers (0)
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!