I am converting a MATLAB code to a C++ and running into small differences b/w my two codes.
For some reason in the C++ code, each term in dVGL is correct when printed out "separately" but somehow when put togther dVGL is incorrect. I get "Inf" and "nan" for some of the values.
I wrote a loop that basically calculates the diagonal matrix given a vector (similar to diag function in MATLAB) and initialized dummy variables that can be used in the final calculation of dVGL.
it may be easier to wire your c++ with extra space and use 1-N instead of 0..N-1 indexing so the code is closer to the same logic and lines.
once you get it debugged, do not be alarmed if the answers are still slightly different. Matlab has all sorts of numerical methods that it chooses from when doing things and those algorithms are not always documented for the user. If you get within some reasonable margin of error to the same answer, I would check it but keep in mind that it could just be close enough.
dummy2[j + ny*i] = 1. * (i); //this multiply just casts, use a cast instead.
So you're right, one thing I was trying to do is have the size of my matrix to be Ny+1 by Ny+1 and wasn't sure how to use memset correctly to do that without returning some error:
malloc(): corrupted top size
Aborted
@jonnin
Not sure what you mean by extra space in the code.
use 1-N instead of 0..N-1 indexing
I am struggling to index properly here for some reason, it isn't as direct as MATLAB. Unfortunately, I am still getting results off with lots of zeros.
okay I guess I see the issue, the C++ code is giving me the diagonal matrix with zeros (off-diagonal terms) of the correct answer, which is interesting. So I though then maybe I need to create a separate loop outside to calculate dVGL like:
@JamieAl, I'm coming into this a bit late, but I noticed in your first code snippet you create a std::vector. Using a C++ container such as a vector removes a lot of the nitty-gritty details of manual memory management and makes it less of a pain.
With a vector you can get/release memory on demand. You can create a sized vector from the start and add/release memory as needed, or create an empty vector and resize as needed.
You've created a 1D vector, creating a true 2D vector (a vector of vectors) isn't that difficult.
Empty: std::vector<std::vector<int>> a2Dvec;
Easier to deal with is one sized at creation:
1 2 3
int row_size { 3 };
int col_size { 4 };
std::vector<std::vector<int>> aSized2DVec(row_size, std::vector<int>(col_size));
With a sized 2D vector you can access the elements using operator[] as if it were a regular 2D array: aSize2DVec[1][2] accesses the 2nd vector (row) and the 3rd element of that vector (column).