Matlab mex function problem

hello, I am trying to use mex function to improve the performance of Matlab. In order to do that, I first tested this sample code (mexfile.c). But I am constantly getting an error which is immediately crashing Matlab. The problem is related to the function, mxCreateCellArray. Here is how I called my mexfile function from Matlab: [x,y,z]=mexfile(rand(3)). I have posted the code below. Please someone help me to solve the problem.
// mexfile.c
#include <stdio.h>
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *input, *output, *output2;
int i, j, n_rows, n_cols;
mwSize size[2];
size[0] = 2;
size[1] = 2;
input = mxGetPr(prhs[0]);
n_rows = mxGetM(prhs[0]);
n_cols = mxGetN(prhs[0]);
if (nlhs == 2) {
plhs[0] = mxCreateDoubleMatrix(n_rows, 1, mxREAL);
output = mxGetPr(plhs[0]);
plhs[1] = mxCreateDoubleMatrix(n_rows, 1, mxREAL);
output2 = mxGetPr(plhs[1]);
plhs[2] = mxCreateCellArray(2, &size);
}
for(i=0; i<n_rows; i++) {
avg = 0.;
for(j=0; j<n_cols; j++) {
avg += input[(i*n_cols)+j];
output2[i] = i;
}
avg /= (double)n_cols;
output[i] = avg;
}
} /* end mexFunction */

 Respuesta aceptada

James Tursa
James Tursa el 18 de Sept. de 2013
Editada: James Tursa el 18 de Sept. de 2013

2 votos

Problem 1)
If nlhs == 2 then there are only two elements allocated for the output, plhs[0] and plhs[1]. You are overwriting the array bounds when you create plhs[2] in this case.
Problem 2)
You call the function with three outputs, so nlhs == 3. Thus you never get inside your if test, so nothing is created for the output, so the output and output2 pointers are invalid, so downstream code using them will bomb.
Problem 3)
I'm not sure what the intent of the function is, so I can't be sure, but you might double check your input[(i*n_cols)+j] indexing. It looks backwards to me. Normally I would expect something like input[i+j*n_rows] instead.
The solution, at least for the code above, appears to be to change the if test to nlhs == 3. And it would be advisable to put more checks in your code. E.g., have an else clause for the nlhs == 3 case that throws an error, check for nrhs == 1, etc.
You can also get rid of the & in the 2nd argument to mxCreateCellArray ... just use size without the &.

Más respuestas (0)

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.

Productos

Etiquetas

Preguntada:

el 18 de Sept. de 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by