I have a problem about mex file!

1 view (last 30 days)
Lucy
Lucy on 31 Aug 2014
Commented: Lucy on 31 Aug 2014
I wrote the following file.c:
#include math.h #include matrix.h #include mex.h
void mexFunction(int nlhs, mxArray * plhs [], int nrhs, const mxArray * prhs []) { double * value; const mwSize * dimx; int nrows, ncolums; int i, j; int lunghy; int valz;
char * stringaval;
value = mxGetPr(prhs[0]);
dimx = mxGetDimensions(prhs[0]);
nrows = (int)dimx [0];
ncolums = (int) dimx [1];
for (i=0; i<nrows;i++)
{
for(j=0; j<ncolums; j++)
{
// stampo il valore float e vado a stampare la prima riga
printf("%f",value [j*nrows+1]);
}
printf("%n");
}
lunghy = (int) mxGetN(prhs[1])+1;
stringaval = mxCalloc(lunghy, sizeof(char));
mxGetString(prhs[1],stringaval,lunghy);
printf("%s",stringaval);
valz = (int) mxGetScalar(prhs[2]);
printf("%d\n",valz);
}
But, when I go to compile it on matlab >>mex mynamefile.c >>mynamefile([1 3 4;-1 -2 -4],'bye',10) matlab closes! I can't understand if there is an error in the code or is my matlab doesn't work. The version I am using is the Matalb R2013b Help me... please!
  4 Comments
Geoff Hayes
Geoff Hayes on 31 Aug 2014
Have you ever built any other MEX-functions? Have you run mex -setup?
Lucy
Lucy on 31 Aug 2014
We've done other MEX-function, some functions work, others not. I have installed the compiler, but in my opinion, I think I have problems on matrices! Photo 1:
<<
>>

Sign in to comment.

Answers (1)

Geoff Hayes
Geoff Hayes on 31 Aug 2014
Lucy - I was able to reproduce the crash; MATLAB does not indeed close when you run the compiled program. The problem is with this line
printf("%n");
I realize that you probably want a carriage return here, after printing out each row of the matrix. So please replace the above line with
printf("\n");
The other line shouldn't cause a crash; even creating the function as a cpp file and including a try/catch block does not prevent this behaviour.
With the above fix, running your program produces
>> g1([1 3 4;-1 -2 -4],'bye',10)
-1.000000-2.000000-4.000000
-1.000000-2.000000-4.000000
bye10
Try the above and see what happens!

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!