[英]Re-writing Matlab code in C++
Basically, I'm trying to split a massive 1D vector into blocks of a given size which is passed through the function. 基本上,我试图将大量的一维矢量分割为给定大小的块,并通过该函数传递。 The function should return a 2D vector and then I can just access the different blocks.
该函数应该返回一个2D向量,然后我就可以访问不同的块了。 I have found a suitable algoritm to do this, however, it is in Matlab and I do not understand how to place the elements inside the 2D vector.
我已经找到合适的算法来做到这一点,但是它在Matlab中,并且我不了解如何将元素放置在2D向量中。
MatLab Code: MatLab代码:
function f = block(v, N, M)
n = length(v);
maxblockstart = n - N + 1;
lastblockstart = maxblockstart - mod(maxblockstart-1 , M);
numblocks = (lastblockstart-1)/M + 1;
f = zeros(numblocks,N);
for i = 1:numblocks
for j = 1:N
f(i,j) = v((i-1)*M+j);
end
end
Here is my attempt in C++ (Sorry if it's bad): 这是我在C ++中的尝试(抱歉,如果不好的话):
vector<iniMatrix> subBlocks(vector<int>& theData, int N, int M)
{
// This method splits the vector into blocks
// Each block has size N.
// and consecutive blocks differ
int n = theData.size();
int maxblockstart = n - N+1;
int lastblockstart = maxblockstart - (maxblockstart-1 % M);
int numblocks = (lastblockstart-1)/M + 1;
vector<int> subBlock;
vector<iniMatrix> block;
for(unsigned i=0; (i < numblocks); i++)
{
for(unsigned j=0; (j < N); j++)
{
subBlock.push_back(theData[(i-1*M+j)]);
block.push_back(subBlock);
}
}
return block;
}
This code compiles, but, when even trying to output the size of the block, i get: Segmentation fault: 11.. Any ideas? 这段代码可以编译,但是,即使尝试输出块的大小,我也会得到:分段错误:11 ..有什么想法吗?
The data being passed through the function is: N = 600 M = 200 通过该函数传递的数据为:N = 600 M = 200
I hope someone can help me, thank you :) 我希望有人可以帮助我,谢谢:)
In c and c++, array indices start from zero. 在c和c ++中,数组索引从零开始。 This is important to keep in mind if you're using array length functions.
如果使用数组长度函数,请记住这一点很重要。 So, you should replace the
i-1
multiplier with i
and start the counting from zero. 所以,你应该更换
i-1
与乘数i
和从零开始计数。 The loop condition: 循环条件:
for (unsigned j=1; (j < N); j++)
will start from 1
and end at the N-1
-- a total of N-1
times. 从
1
开始到N-1
结束-总共N-1
次。 But, 但,
for (unsigned j=0; (j < N); j++)
will start from 0
and end at N-1
-- a total of N
times. 从
0
开始到N-1
结束-总共N
次。
In Matlab: for-loops start from first boundary then end at second boundary 在Matlab中:for循环从第一个边界开始,然后在第二个边界结束
If you feel that you must start from index 1
, 如果您认为必须从索引
1
开始,
for (unsigned j=1; (j < N+1); j++)
will do N
iterations while still starting at 1
. 从
1
开始将进行N
次迭代。 But please keep in mind that when you declare an array in C/C++, the index to the first element is zero. 但是请记住,在C / C ++中声明数组时,第一个元素的索引为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.