我正在将一个函数从 MatLab 转换为 C++,该函数接受一个 vector 并分成包含 600 个值并以 200 为间隔更改的 block 。这是函数(在 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;
这看起来正确吗?我知道这是一个奇怪的问题,我可能会得到负面反馈,但是,我尝试计算过零的数量,但它显示了错误的答案,所以,我拆分 vector 的方式可能有问题。
编辑:
iniMatrix 是二维 vector 的类型定义
产生 96 个 block (包含 600 个值)
最佳答案
你有
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];
关于c++ - 将 vector 拆分为 block - 这是正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384772/