mex sometimes work, sometimes crash

1 view (last 30 days)
zwang
zwang on 20 Mar 2014
Edited: zwang on 20 Mar 2014
In the code I try to calculate the norm for each column of a complex matrix. When I test it in MATLAB 2012b with Mat = rand(500,1000)+1i*rand(500,1000); b = matrixnorm(Mat); I can get the correct answer. But when I use it in my other program, MATLAB is killed every time. Could you give me a hint? below is my code. Thanks in advance.
MATLAB code
#include "mex.h"
#include<omp.h>
#include <math.h>
#include <string.h>
#include "complex"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int coreNum = omp_get_num_procs();
int threadNum=coreNum*4;//coreNum;
omp_set_num_threads(threadNum);
if (nrhs != 1)
mexErrMsgTxt("Wrong number of inputs");
if (nlhs != 1)
mexErrMsgTxt("Wrong number of outputs");
const mxArray *mxA = prhs[0];
if (mxGetNumberOfDimensions(mxA) != 2)
mexErrMsgTxt("Invalid input: A");
const mwSize *A_dims = mxGetDimensions(mxA);
mwSize Out_dims[2];
Out_dims[0] = A_dims[1];
Out_dims[1] = 1;
plhs[0] = mxCreateNumericArray(1,(const mwSize *)Out_dims,mxDOUBLE_CLASS,mxREAL);
double *out = (double *)mxGetPr(plhs[0]);
double *data_imag, *data_real;
data_imag = mxGetPi(prhs[0]);
data_real = mxGetPr(prhs[0]);
int idx; double sum;
#pragma omp parallel for
for(int i = 0;i<A_dims[1];i++)
{
sum = 0;
for(int j = 0;j<A_dims[0];j++)
{
idx = j + i*A_dims[0];
sum = sum + data_imag[idx]*data_imag[idx]+data_real[idx]*data_real[idx];
}
out[i] = sum;
}
}

Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!