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

Performance 减少Matlab中一段代码的执行时间?,performance,matlab,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);

我在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,因为它应用于外部循环)?

让我们来看看-


基准测试

基准测试代码-

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
运行时间为0.237134秒

运行时间为0.026789秒


这些值并不完全相同,但在数值上是等效的。其他列和结果列不同,但您可以看到所需的列。

什么是
n
的典型值?问题已编辑,谢谢
>> error_val = max(abs(others(:)-others_out(:)))
error_val =
   6.2172e-15
 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