如何使用Matlab的bsxfun求解累积和 [英] How to use Matlab's bsxfun to solve cumulative sum
本文介绍了如何使用Matlab的bsxfun求解累积和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下(慢速)代码:
I have the following (slow) piece of code:
% A is n-by-m matrix
% B is n-by-m-by-d matrix
% C is n-by-m-by-d matrix
% R is 1-by-d vector
A=zeros(n,m);
for i=1:d
A = A + sum(B(:,:,1:i),3).*(R(i)-C(:,:,i));
end
我想通过使用神奇的bsxfun来使循环更有效.你能告诉我怎么做吗?
I would like to make it more efficient by using the magical bsxfun to lose the loop. Can you show me how to do that?
推荐答案
这种方式-
A = sum(cumsum(B,3).*bsxfun(@minus,permute(R,[1 3 2]),C),3)
每个尺寸参数为n,m,d
作为200
,则运行时为
With size parameters n,m,d
as 200
each, the runtimes were
----------------------------------- With Proposed Approach
Elapsed time is 0.054771 seconds.
----------------------------------- With Original Approach
Elapsed time is 2.514884 seconds.
使用 bsxfun
和 vectorization
!!
More reasons to use bsxfun
and vectorization
!!
基准代码-
n = 10;
m = 1000;
d = 3;
num_iter = 10000;
B = rand(n,m,d);
C = rand(n,m,d);
R = rand(1,d);
%// Warm up tic/toc.
for k = 1:100000
tic(); elapsed = toc();
end
disp(['********************* d = ' num2str(d) ' ************************'])
disp('----------------------------------- With Proposed Approach')
tic
for iter = 1:num_iter
A1 = sum(cumsum(B,3).*bsxfun(@minus,permute(R,[1 3 2]),C),3);
end
toc
disp('----------------------------------- With Original Approach')
tic
for iter = 1:num_iter
A = zeros(n,m);
for i=1:d
A = A + sum(B(:,:,1:i),3).*(R(i)-C(:,:,i));
end
end
toc
我的运行时是-
********************* d = 3 ************************
----------------------------------- With Proposed Approach
Elapsed time is 0.856972 seconds.
----------------------------------- With Original Approach
Elapsed time is 1.703564 seconds.
********************* d = 9 ************************
----------------------------------- With Proposed Approach
Elapsed time is 2.098253 seconds.
----------------------------------- With Original Approach
Elapsed time is 9.518418 seconds.
这篇关于如何使用Matlab的bsxfun求解累积和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文