Octave / Matlab中的琐碎/不可能的算法挑战 - 迭代内存

时间:2015-12-02 15:11:49

标签: algorithm performance matlab octave vectorization

有一个输入向量,其值为{-2,-1,0,1,2},例如

input = [2 2 2 2 0 1 0 -1 0 -2 -2 -1 0 1]

从开始到结束迭代地扫描向量,并且在每个点处基于向量的当前值和由先前迭代确定的特定累积值来实现某个转换表。此值按请求的步骤(此处为3)递增/递减,直到最高值(此处为9),超出该值不能超过该值。 输出向量表示根据定义的转换从当前输入值和累积中导出的某些正在进行的增量。

Octave(3.8)中的循环表现非常糟糕,我无法找到一种方法来对此进行矢量化。在输入和输出之间使用这种间接的累积记忆时,矢量化是否可行?

input = [2 2 2 2 0 1 0 -1 0 -2 -2 -1 0 1] 
step  = 3;
top   = 9;
acc = out = 0;

for i = 1 : length(input) 
  if     (input(i) == +2) 
          if (acc <         0) out(i) = -acc+step; 
      elseif (acc >  top-step) out(i) = 0; 
      elseif (acc >=        0) out(i) = step; 
       endif 
  elseif (input(i) == +1) 
          if (acc >=        0) out(i) = 0; 
      elseif (acc <         0) out(i) = -acc; 
       endif 
  elseif (input(i) ==  0)      out(i) = 0; 
  elseif (input(i) == -1) 
          if (acc <=        0) out(i) = 0; 
      elseif (acc >         0) out(i) = -acc; 
       endif 
  elseif (input(i) == -2) 
          if (acc >         0) out(i) = -acc-step; 
      elseif (acc < -top+step) out(i) = 0; 
      elseif (acc <=        0) out(i) = -step; 
       endif 
  endif 
  acc += out(i);
endfor
out

out =
3 3 3 0 0 0 0 -9 0 -3 -3 0 0 6
# e.g. the -9 resets the first three 3's buildup: 3+3+3-9=0

性能bechmark:

解决方案1(慢速循环)

(修改)

input = repmat([2 2 2 2 0 1 0 -1 0 -2 -2 -1 0 1], 1,20000);
out   = zeros(1, length(input));
tic; for i = 1 : length(input) 
  (...)
endfor; toc;
Elapsed time is 8.95053 seconds.

0 个答案:

没有答案