MATLAB: Mex file crash after second run.

bugimage processingmex

Hi there,
I just wrote my first mex file and am finding my matlab crashes the second time I try to run my compiled mex file. The only way I can overcome this issue is by closing matlab and reopening it before I run the mex file again. I would most appreciate it if someone could please help me overcome this issue.
Info on code: This file was made to pass in a 3D image volume from matlab, convert the image vector back into a 3D matrix after it is passed into the mex file, and then output the image as a vector after I have processed the data. Below I have my script that I use to load the 3D mri test data set from matlab, compile a mex file, and run the mex file and the actual .cpp file I created. Just note the mri volume dimension was converted from a 4D matrix into a (128 X 128 X 27) matrix and they were hard coded into my code. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Script File:
clear all close all clc
load mri I(:,:,:) = double(D(:,:,1,:));
mex Image.cpp
s = Image(I);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% .Cpp file #include mex.h #include math.h
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwSize r,c, i,j,k, n; mwSize Ndims; const mwSize *dims;
dims = mxGetDimensions(prhs[0]);
Ndims = mxGetNumberOfDimensions(prhs[0]);
/* get size of the matrix */
r = mxGetM(prhs[0]);
c = mxGetN(prhs[0]);
double *input;
double output[128*128*27];
double temp[128][128][27];
/* get pointer to data */
input = mxGetPr(prhs[0]);
/* access matrix using row/column indices */
mwSize count = 0;
for (i=0; i<128; i++) {
for (j=0; j<128; j++) {
for (k=0; k<27; k++) {
temp[i][j][k] = input[count] * input[count];
count++;
}
}
}
count = 0;
for (i=0; i<128; i++) {
for (j=0; j<128; j++) {
for (k=0; k<27; k++) {
output[count] = temp[i][j][k];
count++;
}
}
}
/* Create a matrix for the return argument */
plhs[0] = mxCreateNumericArray(Ndims,dims,mxDOUBLE_CLASS,mxREAL);
mxSetPr(plhs[0], output);
return;
}

Best Answer

Hi Jon,
the problem is, you use the temporary memory of output in mxSetPr. mxSetPr does not copy but only set's the pointer. At the end of your mex function the variable output is destroyed (and therefore the data of plhs[0] as well!).
What you have to do: move the mxCreateNumericArray before the loops, and use mxGetPr to retrieve output pointer. Then fill up the entries.
Titus