这可以优化以在MATLAB中更快地运行吗?

时间:2015-11-17 18:03:17

标签: matlab loops optimization vectorization

这是代码

S = size(shape,3)
shape = 1 - shape;

for i = 2:S
    SHAPE = prod(shape(:,:,1:i-1),3);
    for c = 1:3
        vision(:,:,c,i) = vision(:,:,c,i).*SHAPE;
    end
end

output = sum(vision,4);

也许有办法对其进行矢量化?

顺便说一下shapeSHAPE是零和一的数组,所以它们可能以某种方式用作逻辑。

1 个答案:

答案 0 :(得分:5)

这是一个更多 bsxfun解决方案 -

S = size(shape,3);
shape = 1 - shape;

SHAPE = cumprod(shape(:,:,1:S-1),3);
vision(:,:,1:3,2:S) = bsxfun(@times,vision(:,:,1:3,2:S),permute(SHAPE,[1 2 4 3]));
output = sum(vision,4);

<强>测试

由于代码有vision(:,:,c,i)且迭代器c来自c = 1:3,因此vision的第三维很可能是3。要验证提议的方法是否有效,请将其保留为5。此外,为了进行适当的基准测试,让我们在其他维度上拥有大数字,并且让它们中包含随机数。为了验证,最后我们会发现建议和原始方法的输出之间的绝对最大差异。

基准测试和输出验证码 -

% Inputs
shape = rand(150,160,170);
vision = rand(150,160,5,170);
shape = 1 - shape;
S = size(shape,3);

%// Proposed solution :
disp('----------------------- With Proposed solution')
tic
V = vision;   %// Make a copy for using with proposed solution
SHAPE = cumprod(shape(:,:,1:S-1),3);
V(:,:,1:3,2:S) = bsxfun(@times,V(:,:,1:3,2:S),permute(SHAPE,[1 2 4 3]));
out = sum(V,4);
toc

%// Original solution :
disp('----------------------- With Original solution')
tic
S = size(shape,3);
for i = 2:S
    SHAPE = prod(shape(:,:,1:i-1),3);
    for c = 1:3
        vision(:,:,c,i) = vision(:,:,c,i).*SHAPE;
    end
end
output = sum(vision,4);
toc

error_value = max(abs(output(:) - out(:)))

命令输出 -

----------------------- With Proposed solution
Elapsed time is 0.802486 seconds.
----------------------- With Original solution
Elapsed time is 4.401897 seconds.
error_value =
     0