【发布时间】:2014-02-11 23:02:31
【问题描述】:
我正在编写一个计算某种矩阵的 Matlab 应用程序。我正在尝试用基于向量的计算替换程序中的 for 循环,但是,我被卡住了。
到目前为止,我已经想到了这个简单的示例代码部分:
kernel = zeros(5,5,5);
offset = 3;
sig=1;
for x=-2:2
for y=-2:2
for z=-2:2
IN = x.^2/(sig^2) + y.^2/(sig^2) + z.^2/(sig^2);
kernel(offset+x, offset+y, offset+z) = exp(-IN/2);
end
end
end
可以用这样的结构代替:
[x,y,z] = ndgrid(-2:2,-2:2,-2:2);
IN = x.^2/(sig^2) + y.^2/(sig^2) + z.^2/(sig^2);
kernel = exp(-IN/2);
并给出相同的结果。 但是如果我需要做一些小改动怎么办:
kernel = zeros(5,5,5);
offset = 3;
sig=1;
%sample 3x3 matrix
R=magic(3)/10;
for x=-2:2
for y=-2:2
for z=-2:2
% calculation of new x, y, z
point = [x,y,z]*R;
IN = (point(1)^2 )/(sig^2) + (point(2)^2)/(sig^2) + (point(3)^2)/(sig^2);
kernel(offset+x, offset+y, offset+z) = exp(-IN/2);
end
end
end
如何加快构建速度?它可以很容易地矢量化吗?我对 Matlab 很陌生,所以我将不胜感激。非常感谢!
【问题讨论】:
标签: performance matlab vector vectorization