0

我得到了一个 MATLAB 函数,它接受一个 1D 向量和两种大小,然后该函数将数据拆分为块,最后将它们存储在 2D 向量中。我一直在编写这个函数的 C++ 版本,但是我的 C++ 函数的(不正确的)结果与 MATLAB 函数的(正确的)结果不匹配。

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

出于本示例的目的,我只是输出 ((i-1)*M+j) 的结果,在 MatLab 中我得到这些结果(示例):

1 201 401 601 .. 1001 1201 .. 1401 .. 1601 .. 1801

这是我的 C++ 函数:

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;
}

我从中得到的结果:

1 2 3 4 .. 7 8 9 .. 13 14 15 等..

附言

iniMatrix 只是浮点向量的 typdef ..

另一个注意事项,变量:

n

最大块启动

最后一个块开始

数字块

在 Matlab 程序和 C++ 中都具有相同的值,所以我认为这与 for 循环有关。

有人有什么建议吗?

4

2 回答 2

1

我不确定,但你在哪里写输出中的一维向量的值?

也许你需要改变这个:

  for i = 1:numblocks
  for j = 1:N
   f(i,j) = v((i-1)*M+j);
  end 
 end
于 2012-09-18T20:27:04.110 回答
1

让我看看我是否正确理解了您想要的算法。说 n = 10 N = 3 M = 2

这应该产生 0、2、4、6 对吧?(因为 8 不适合,因为 8+M 超出范围 0 <= x < n)。

所以,maxblockstart 应该是 7 = 10 - 3,即 n - N

lastblockstart 应该是 6 = 7 - 7 % 2,即 maxblockstart - maxblockstart % M

并且 numblocks 应该是 4 = 6/2 + 1,即 lastblockstart/M + 1

如下修改你的代码,似乎产生了正确的结果(只在纸上解决了这个问题,没有尝试编译或执行......):

vector<iniMatrix> Audio::subBlocks(vector<float>& theData, int N, int M)
{
  int n = theData.size();
  int maxblockstart = n - N;
  int lastblockstart = maxblockstart - (maxblockstart % M);

  int numblocks = (lastblockstart)/M + 1;

  vector<iniMatrix> block;    

  for(int i=0; (i < numblocks); i++)
  {
     vector<float> subBlock;
      for(int j=0; (j < N); j++)
      {
          subBlock.push_back(theData[i*M+j]); //cout << (i*M+j);
      }  
      block.push_back(subBlock);
  }

  return block;
}

试试看...

请注意,将结果与 MATLAB 进行比较可能会造成混淆,因为 C++ 指示是从零开始的。因此尝试以下操作;

1)将行更改cout << (i*M+j);cout << theData[i*M+j];

2)尝试以下测试:

vector<float> test;
for(int i=0; i<=10000; i++)
  test.push_back(i);

Audio::subBlocks(test, 1023, 200);
于 2012-09-18T20:28:13.163 回答