简体   繁体   English

如何在Matlab中向量化两个for循环以加快速度

[英]How to vectorize two for loops in matlab for speed up

How can I speed up the two for loops below by vectorization in MATLAB? 如何通过MATLAB中的向量化来加速下面的两个for循环? This is a part of an iterative algorithm and I need to do it many times. 这是迭代算法的一部分,我需要做很多次。

Temp1=0;
Temp2=0;

for i=1:m_plus
    for j=1:m_minus
        Temp1=Temp1+(p_m(j,:)-p_p(i,:))';
        Temp2=Temp2+(p_m(j,:)-p_p(i,:))'*(p_m(j,:)-p_p(i,:));
    end
end

Assuming 假设

m_plus = size(p_p,1);
m_minus = size(p_m,1);

then it's easy enough to do Temp1 without loops 那么就很容易进行不带循环的Temp1

Temp1 = (m_plus*sum(p_m)-m_minus*sum(p_p))'

For Temp2 it's easy to get rid of one of the loops, 对于Temp2 ,摆脱其中一个循环很容易,

Temp2 = 0;
for idx = 1:m_plus
    temp = p_m-ones(m_minus,1)*p_p(idx,:); % or could use bsxfun to do this
    Temp2 = Temp2 + temp'*temp;
end

although with a little more thought it may be possible to get rid of this loop too. 尽管稍加思考,也有可能摆脱这种循环。

Another vectorized approach that is sort of inspired from Phil's smart answer - Phil的聪明回答中得到启发的另一种矢量化方法是-

t1 = bsxfun(@minus,p_m,permute(p_p,[3 2 1]));
t2 = reshape(permute(t1,[1 3 2]),m_minus*m_plus,[]);
Temp1 = sum(t2)'; %//'
Temp2 = t2'*t2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM