Yasin
Yasin

Reputation: 619

Converting this C++ code to Matlab

I'm trying to convert a straight-forward C code to matlab but I got stuck in something that seemed to be quite clear at first. What's this segment doing? SIZE_N2 = 25, w = 533, h = 800

//Init the L matrix. L is a sparse matrix that only contains SIZE_N2 non-zero elements per row.
//We store the L matrix in an array with one row per image pixel and one column per non-zero value. 
//Each array cell accumulates values according to equation 11.
LMatrix = new double* [w*h];
for(i=0; i<w*h; i++){
    LMatrix[i] = new double[SIZE_N2];
    for(j=0; j<SIZE_N2; j++){
        LMatrix[i][j] = 0;
    }
}

Isn't it creating this matrix in Matlab?

LMatrix = zeros(SIZE_N2, w*h);

When I run the code with this, the matrix goes out of bound on a for loop.

Anyone knows the right implementation of this?

Thanks!

Upvotes: 0

Views: 106

Answers (2)

cfh
cfh

Reputation: 4666

The most straightforward translation of your C++ code into MATLAB would be

LMatrix = zeros(w*h, SIZE_N2)

Note that the first index (number of rows) in the code has size w*h, and you swapped them around. This is why you got out of bounds errors, because you indexed the wrong way around.

I'll also mention that C++ uses 0-based indexing, while MATLAB uses 1-based indexing. This will trip you up, and you have to be very, very careful to always add 1 to your indices when translating the code.

Upvotes: 0

Dev-iL
Dev-iL

Reputation: 24169

First of all, it would be helpful to reference the entirety of the source code (just in case) and some documentation about it (so we know, for example, what "equation 11" is).

Now, if I understand the code correctly, everything (including the loops) could be replaced in MATLAB with the following:

LMatrix = sparse([],[],[],w*h,w*h,SIZE_N2*h);

Unless you know in advance where the nonzero elements should be, in which case you could just construct the final sparse matrix right there and then, using one of the other syntaxes (docs1, docs2).

Upvotes: 1

Related Questions