简体   繁体   English

将此C ++代码转换为Matlab

[英]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. 我正在尝试将简单的C代码转换为matlab,但是一开始我似乎很清楚地陷入了困境。 What's this segment doing? 该细分市场在做什么? SIZE_N2 = 25, w = 533, h = 800 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? 它不是在Matlab中创建此矩阵吗?

LMatrix = zeros(SIZE_N2, w*h); LMatrix = 0(SIZE_N2,w * h);

When I run the code with this, the matrix goes out of bound on a for loop. 当我用它运行代码时,矩阵在for循环中超出范围。

Anyone knows the right implementation of this? 任何人都知道正确的实现吗?

Thanks! 谢谢!

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). 首先,参考整个源代码 (以防万一)和有关它的一些文档 (例如,我们知道什么是“ 等式11 ”)将很有帮助。

Now, if I understand the code correctly, everything (including the loops) could be replaced in MATLAB with the following: 现在,如果我正确理解了代码,则可以在MATLAB中将所有内容(包括循环)替换为以下内容:

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 ). 除非您事先知道非零元素应该在哪里,否则您可以在那儿构造最终的稀疏矩阵,然后使用其他语法之一( docs1docs2 )。

The most straightforward translation of your C++ code into MATLAB would be 将C ++代码转换为MATLAB最直接的方法是

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. 请注意,代码中的第一个索引(行数)的大小为w*h ,您将它们交换了一下。 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. 我还将提到C ++使用基于0的索引,而MATLAB使用基于1的索引。 This will trip you up, and you have to be very, very careful to always add 1 to your indices when translating the code. 会使您绊倒,在转换代码时,必须非常非常小心地始终向索引加1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM