1

我正在将一个函数从 MatLab 转换为 C++,该函数接受一个向量并分成包含 600 个值并以 200 个间隔更改的块。这是函数(在 MatLab 中):

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) = v((i-1)*M+j);
end

结尾

以及 C++ 中的函数:

vector< iniMatrix > Audio::something(vector<double>& theData, int N, int M)
{
//How many blocks of size N can we get?
int num_blocks = theData.size() / N;

int n = theData.size();
int maxblockstart = n - N;
int lastblockstart = maxblockstart - (maxblockstart % M);
int numbblocks = (lastblockstart)/M + 1;

this->width = N;

//Create the vector with enough empty slots for num_blocks blocks
vector<iniMatrix> blocked(num_blocks);

//Loop over all the blocks
for(int i = 0; i < num_blocks; i++) {
    //Resize the inner vector to fit this block            
    blocked[i].resize(N);

    //Pull each sample for this block
    for(int j = 0; j < N; j++) {
        blocked[i][j] = theData[i*N+j];
    }
}
return blocked;

}

这看起来正确吗?我知道这是一个奇怪的问题,我可能会得到负面反馈但是,我尝试计算过零的数量并且它显示了错误的答案,所以,也许我拆分向量的方式有问题。

编辑:

iniMatrix 是 2D 向量的 typedef

产生 96 个块(包含 600 个值)

4

1 回答 1

1

你有

f(i,j) = v((i-1)*M+j);

在 Matlab 代码的最后一个循环中,但在 C++ 代码中是

blocked[i][j] = theData[i*N+j];

似乎有可能导致错误的印刷错误。例如,您需要使用 C++ 编写代码:

blocked[i][j] = theData[i*M+j];
于 2012-11-15T05:55:19.120 回答