Ale*_*zel 1 optimization matlab loops 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);
Run Code Online (Sandbox Code Playgroud)
也许有一种方法来矢量化它?
顺便说一下shape,SHAPE它们是0和1的数组,因此它们可能以某种方式被用作逻辑.
这里有一个更 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);
Run Code Online (Sandbox Code Playgroud)
测试
由于代码具有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(:)))
Run Code Online (Sandbox Code Playgroud)
命令输出 -
----------------------- With Proposed solution
Elapsed time is 0.802486 seconds.
----------------------- With Original solution
Elapsed time is 4.401897 seconds.
error_value =
0
Run Code Online (Sandbox Code Playgroud)