How to find my numerical bug when calling C++ with MATLAB to do matrix copy?

  c++, matlab, mex

I have compiled mex file from C++ code:

#include "mex.h"
#include "matrix.h"
#include "fdtd-macro.h"
#include "copyMatrix.cpp"
#include "global_var.h"
int nx,ny,nz,linearSizeEx,linearSizeEy,linearSizeEz;
int ExM,ExN,ExP,EyM,EyN,EyP,EzM,EzN,EzP,HxM,HxN,HxP,HyM,HyN,HyP,HzM,HzN,HzP;
double *Ex,*Ey,*Ez,*tmpEx,*tmpEy,*tmpEz;
const mwSize  *dimEx,*dimEy,*dimEz;
const mwSize  *dimCexe,*dimCexhy,*dimCexhz,*dimCeye,*dimCeyhx,*dimCeyhz,*dimCeze,*dimCezhx,*dimCezhy;
using namespace std;
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
    //read input from MATLAB calling
    Ex = mxGetPr(prhs[0]);          Ey = mxGetPr(prhs[1]);          Ez = mxGetPr(prhs[2]);
    tmpEx = mxGetPr(prhs[3]);       tmpEy = mxGetPr(prhs[4]);       tmpEz = mxGetPr(prhs[5]);
    dimEx = mxGetDimensions(prhs[0]);   dimEy = mxGetDimensions(prhs[1]);   dimEz = mxGetDimensions(prhs[2]);
    //dimensions
    ExM = dimEx[0];     ExN = dimEx[1];     ExP = dimEx[2];
    EyM = dimEy[0];     EyN = dimEy[1];     EyP = dimEy[2];
    EzM = dimEz[0];     EzN = dimEz[1];     EzP = dimEz[2];
    linearSizeEx = (ExP-1)*ExN*ExM+(ExN-1)*ExM+ExM-1;
    linearSizeEy = (EyP-1)*EyN*EyM+(EyN-1)*EyM+EyM-1;
    linearSizeEz = (EzP-1)*EzN*EzM+(EzN-1)*EzM+EzM-1;
//copy E field to temporary E field
    copyMatrix(tmpEx,Ex,linearSizeEx);
//     copyMatrix(tmpEy,Ey,linearSizeEy);
//     copyMatrix(tmpEz,Ez,linearSizeEz);
    return;
}

My goal is to copy Ex to tmpEx. My code has passed compilation and I have tested that it indeed copied Ex to tmpEx correctly. but when I finally call the compiled mex file with

updateElectricFields(Ex,Ey,Ez,Ex_temp,Ey_temp,Ez_temp);

It cause my algorithm to explode with values of 10 to the power of hundreds. The code for copying matrix is listed here:


void copyMatrix(double *A,double *B,int linearSize)
{
    int ii;
    for (ii = 0;ii<linearSize+1;ii++)
        A[ii] = B[ii];
    return;
}

Where could the problem be?
The diverged result

Source: Windows Questions C++

LEAVE A COMMENT