I am having an issue converting simple expressions from MATLAB to c++. I believe maybe my order of operations or the place of my paranthesis is causing me a lot of pain. The outputs from the two codes aren't matching for some reason.
C++ code:
// Set domain size parameters.
double Lx = 128.;
double Ly = 128.;
int nx = 128;
int ny = 128;
double dx = Lx / nx;
double dy = Ly / ny;
// init XX, YY and calculate their values
for (int i = 0; i < nx; i++){
for (int j = 0; j < ny; j++){
rho_exact[j + ny*i] = (1./13.) * pow((Lx/(2.*M_PI)),2.) * cos( ((2.*M_PI *2.)/ Lx) * XX[j+ny*i]) * sin( ((2. *M_PI * 3.)/ Ly) * YY[j+ny*i]);
}
}
It seems as if the problem arises from the cosine term, my XX (2D arrays) are matching from both codes so it I am only left to believe my syntax or logic here isn't great.
you do not want to 'fix' it. iteration should be done in a way that touches cells sequentially in memory, or you get more page faults and bad performance. so you write the C++ to access it row major, and matlab will do its thing. this means you sometimes write your own methods as if working on a transposed matrix...
if trying to use a c++ library you did not write and matlab, it may simply be in your best interest to let matlab transpose it for you before exporting the data.
you may want to check the file formats too, if you export via a binary file. There may be a flag to flip it there.
it is a bit of trouble to mix libraries that use different ordering. Somewhere, you have to pay for a transpose, in most cases. Are you trying to use matlab's C interface dlls or anything like that?
Are you trying to use matlab's C interface dlls or anything like that?
No, not really. This was part of a test I was running to make sure one of my functions is working properly. Just try to solve for an equation that I know the exact solution to. I used MATLAB since to compare my outputs.
I can just take the transpose in MATLAB like: phi_exact ' but somehow that's still off from the C++ output.
could be anything... roundoff, real or print-caused, bug, numerical methods in play (matlab... one of several reasons it is so slow is all the normalization, factorization, and other error reduction in play) ... or other reasons. I never found a great approach here, I always just printed the result of each step in both C & M to see what step went wrong and debugged it from there.
it is rare to get exact same answer from C & M ... expect minor variation on floating point results.
Really, you're absolutely right. What's weird is that I can load both outputs in MATALB and plot them (another easy way to check my answers) and the plots look fine, actually almost identical!