简体   繁体   中英

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. 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-1 multiplier with i and start the counting from zero. 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. But,

for (unsigned j=0; (j < N); j++)

will start from 0 and end at N-1 -- a total of N times.

In Matlab: for-loops start from first boundary then end at second boundary

If you feel that you must start from index 1 ,

for (unsigned j=1; (j < N+1); j++)

will do N iterations while still starting at 1 . But please keep in mind that when you declare an array in C/C++, the index to the first element is zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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