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. 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 Code:
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):
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?
The data being passed through the function is:
N = 600
M = 200
I hope someone can help me, thank you 🙂
In c and c++, array indices start from zero. This is important to keep in mind if you’re using array length functions. So, you should replace the
i-1multiplier withiand start the counting from zero. The loop condition:will start from
1and end at theN-1— a total ofN-1times. But,will start from
0and end atN-1— a total ofNtimes.In Matlab: for-loops start from first boundary then end at second boundary
If you feel that you must start from index
1,will do
Niterations while still starting at1. But please keep in mind that when you declare an array in C/C++, the index to the first element is zero.