I’ve been given a MATLAB function that takes in a 1D vector and two sizes, the function then splits the data into blocks and finally stores them inside a 2D vector. I have been writing a C++ version of this function, but the (incorrect) results of my C++ function do not match the (correct) results of the MATLAB function.
Matlab function:
function f = block(v, N, M)
% This function separates the vector
% into blocks. Each block has size N.
% and consecutive blocks differ in
% their starting positions by M
%
% Typically
% N = 30 msec (600 samples)
% M = 10 msec (200 samples)
n = length(v);
maxblockstart = n - N + 1;
lastblockstart = maxblockstart - mod(maxblockstart-1 , M);
% Remove the semicolon to see the number of blocks
% numblocks = (lastblockstart-1)/M + 1
numblocks = (lastblockstart-1)/M + 1;
%f = zeros(numblocks,N);
for i = 1:numblocks
for j = 1:N
f(i,j) = ((i-1)*M+j);
end
end
For the purpose of this example, I’m just outputting the results of ((i-1)*M+j) and in MatLab I get these results (example):
1 201 401 601 .. 1001 1201 .. 1401 .. 1601 .. 1801
And here is my C++ function:
vector<iniMatrix> Audio::subBlocks(vector<float>& 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 - mod(maxblockstart-1, M);
int numblocks = (lastblockstart-1)/M + 1;
vector<float> subBlock;
vector<iniMatrix> block;
for(int i=1; (i < numblocks); i++)
{
for(int j=1; (j < N); j++)
{
cout << ((i-1)*M+j);
}
}
return block;
}
The result I get from this:
1 2 3 4 .. 7 8 9 .. 13 14 15 etc..
P.S.
iniMatrix is just a typdef for the a vector of floats..
Another note, the variables:
n
maxblockstart
lastblockstart
numblocks
All have the same value in the Matlab program and the C++ so I think it’s something to do with the for loops..
Anyone have any suggestions?
Let me see if I’ve understood your desired algorithm correctly.
Say
n = 10
N = 3
M = 2
This should yield
0, 2, 4, 6 right? (since 8 won’t fit because 8+M is outside the range 0 <= x < n).
So, maxblockstart should be 7 = 10 – 3, that is n – N
lastblockstart should be 6 = 7 – 7 % 2, that is maxblockstart – maxblockstart % M
and numblocks should be 4 = 6/2 + 1, that is lastblockstart/M + 1
Modifying your code as follows, seems to yield the right results (only worked this out on paper, haven’t tried compiling or executing…..):
Give it a try…
Note that comparing results against MATLAB can be confusing, since C++ indicing is zero-based. Thus try the following;
1) Change the line
cout << (i*M+j);tocout << theData[i*M+j];2) Try the following test: