Crash with a mex file, using mxMalloc, mxCalloc and complex vectors
显示 更早的评论
Hi,
I am trying to write a mex file but I can't find out what does not work in it. I have "emptied" it and wrote a test one but it still doesn't work. Matlab is killed each time I try to run it. To run it, I take a random signal: x = randn(1,16); and then type y = test(x) Could you give me a hint? Here is the code:
#include <stdlib.h>
#include <string.h>
#include <math.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/utsname.h>
#endif
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int N, *partitions;
int taille, i;
double *partdouble;
double *sigi, *sigr, *gftr, *gfti, *win, *signal, *gft;
char *windowtype;
void *window;
/* create a pointer to the real data in the input matrix */
sigr = mxGetPr(prhs[0]);
signal = mxMalloc(2*N*sizeof(mxCOMPLEX));
/* get dimensions of the input matrix */
N = mxGetM(prhs[0]);
if (N == 1)
N = mxGetN(prhs[0]);
/* If not complex, set imaginary part to 0 */
if (!mxIsComplex(prhs[0]))
sigi = mxCalloc(N, sizeof(mxREAL));
else
sigi = mxGetPi(prhs[0]);
/* In C, real and complex values are interleaved whereas in Matlab
* there are split. Therefore create a complex signal of size 2N with 0
* interleaved as the original signal is real */
for (i = 0; i<N; i++) {
signal[i] = sigr[i];
signal[2*i+1] = sigi[i];
}
/* create the output matrix */
plhs[0] = mxCreateDoubleMatrix(1,N, mxCOMPLEX);
/* get a pointer to the real data in the output matrix */
gftr = mxGetPr(plhs[0]);
gfti = mxGetPi(plhs[0]);
gft = mxCalloc(N,sizeof(mxCOMPLEX));
for (i=0; i<2*N; i++){
gft[i] = signal[i];
}
for (i = 0; i<N; i++) {
mexPrintf("gft[%d] = %lf\t gft[%d] = %lf\n", 2*i, gft[2*i], 2*i+1, gft[2*i+1]);
gftr[i] = gft[2*i];
gfti[i] = gft[2*i+1];
}
mexPrintf("The end\n");
}
One of the side questions is that as signal should be an N-complex vector, should I declare it as signal = mxMalloc(2*N*sizeof(mxCOMPLEX)); or signal = mxMalloc(N*sizeof(mxCOMPLEX));? Cheers, Carine
采纳的回答
更多回答(2 个)
James Tursa
2012-10-8
You use N before you set its value:
signal = mxMalloc(2*N*sizeof(mxCOMPLEX)); // Use it here
/* get dimensions of the input matrix */
N = mxGetM(prhs[0]); // Set its value here
Also, you should not be using sizeof(mxCOMPLEX) or sizeof(mxREAL) for memory allocation. mxCOMPLEX and mxREAL are enumeration integer values used as flags in API calls ... they are not the data type itself. In your memory allocation:
signal = mxMalloc(2*N*sizeof(*signal));
:
sigi = mxCalloc(N, sizeof(*sigi));
:
gft = mxCalloc(2*N,sizeof(*gft));
In addition, for the complex ones that you had you may need to use 2*N instead of N as noted.
类别
在 帮助中心 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!