减少Matlab中一段代码的执行时间?

时间:2015-09-21 17:08:17

标签: performance matlab

我在Matlab中有以下代码

    n=15
    eqtocheck=randn(196584,17);
    tic 
    others=zeros(size(eqtocheck,1),n-1); 
    for i=1:n-1
        behavothers=eqtocheck(:,3:end);
        behavothers(:,i)=[];
        others(:,i)=sum(behavothers,2); 
                   %for each kth row of eqtocheck, 
                   %sum all elements of the row except the ith element 
                   %and report the sum in the (k,i) element of others
    end
    toc

用Matlab-r2015a运行它需要大约0.25秒。你能否建议一种缩短执行时间的方法(我不能使用parfor,因为它应用于外部循环)?

2 个答案:

答案 0 :(得分:3)

让我们bsxfun -

A = eqtocheck(:,3:end);
others = bsxfun(@minus,sum(A,2),A(:,1:end-1));

<强>基准

基准代码 -

n=15;
eqtocheck=randn(196584,17);

disp('---------------- Before BSXFUNing -------------')
tic
others=zeros(size(eqtocheck,1),n-1);
for i=1:n-1
    behavothers=eqtocheck(:,3:end);
    behavothers(:,i)=[];
    others(:,i)=sum(behavothers,2);
end
toc

disp('---------------- After BSXFUNing -------------')
tic
A = eqtocheck(:,3:end);
others_out = bsxfun(@minus,sum(A,2),A(:,1:end-1));
toc

运行时 -

---------------- Before BSXFUNing -------------
Elapsed time is 0.759202 seconds.
---------------- After BSXFUNing -------------
Elapsed time is 0.069710 seconds.

验证结果 -

>> error_val = max(abs(others(:)-others_out(:)))
error_val =
   6.2172e-15

答案 1 :(得分:0)

 n=13
eqtocheck=randn(196584,16);
tic
others=zeros(size(eqtocheck,1),16);
for i=1:n-1
    behavothers=eqtocheck(:,3:end);
    behavothers(:,i)=[];
    others(:,i)=sum(behavothers,2);
    %for each kth row of eqtocheck,
    %sum all elements of the row except the ith element
    %and report the sum in the (k,i) element of others
end
toc
% using straight math with repmat to expand the matrix
tic
values = eqtocheck(:,3:end);
tempsum = sum(values, 2);
tempsum2 = repmat(tempsum, 1, n + 1);
result = tempsum2 - values;
toc

经过的时间是0.237134秒。

经过的时间是0.026789秒。

值不完全相同,但它们在数值上是等价的。其他列和结果之间的列不同,但您可以看到您想要的列。