我有以下要矢量化的 for 循环。但是,在 for 循环中我使用了 circshift。有没有办法使用矢量化执行 for 循环,或者至少对其进行优化?随着 strt、stop 和 M 增加它们的大小,它运行得非常慢。
indx = 0;
M = magic(16);
v = M(:,1);
strt=-5;
stop=+5;
result = zeros(4, length(strt:stop), 4);
for ii=strt:stop
tmp = circshift(M, [0 ii])*v;
tmp = tmp/norm(tmp);
indx = indx+1;
result(:, indx, :) = reshape( tmp(:,1), 4,4);
end
最佳答案
用 circshift
移动那个巨大的 2D
数组,M
肯定会很昂贵。因此,一个技巧可能是围绕 1D
数组 v
向另一个方向移动,并保持 M
不变。所以,我们只需要一个编辑来替换:
circshift(M, [0 ii])*v
和 M*circshift(v,-ii)
。
M
的运行时为 (2500 x 2500)
大小的数组,在我这边原始和建议的方法是 -
----------------------- With Original approach
Elapsed time is 0.803823 seconds.
----------------------- With Proposed approach
Elapsed time is 0.137444 seconds.
关于performance - MATLAB:向量化包含 circshift 的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598263/