简体   繁体   English

Vectorize Double Loop - MATLAB

[英]Vectorize Double Loop - MATLAB

I have a double loop, which is very inefficient. 我有一个双循环,这是非常低效的。

c is a [400,2000] matrix
r is a [2000,1] matrix
P is a [2000,1] matrix
S is a [1, 400] matrix


for i=1:400
    for k=1:2000
        c(i,k) = r(k,1) * max([0, P(k,1) - S(1,i)]);
    end
end

I tried to make a parfor and it worked. 我试图制作一个parfor并且它有效。 But I was looking for a more elegant solution. 但我一直在寻找更优雅的解决方案。 I have been trying and trying but no luck... 我一直在努力尝试但没有运气......

As you are only doing element-wise operations, as - , and .* , this calls for a solution using bsxfun . 因为你只是做元素操作,如-.* ,这需要使用bsxfun的解决方案。

Use 采用

bsxfun(@minus,P,S)

to do an element-wise subtraction P(k,1) - S(1,i) . 做元素减法P(k,1) - S(1,i) The output will be a [2000,400] matrix. 输出将是[2000,400]矩阵。 You can apply the max(0,...) operation on this matrix, and finally use bsxfun again to multiplicate each row by the corresponding r : 您可以对此矩阵应用max(0,...)运算,最后再次使用bsxfun将每一行乘以相应的r

bsxfun(@times,max(bsxfun(@minus,P,S),0),r)

As your c should be of size [400,2000] , add a final transpose operation, and you're finished. 由于你的c应该是[400,2000]的大小,添加一个最终的转置操作,你就完成了。

c = bsxfun(@times,max(bsxfun(@minus,P,S),0),r).';

A small time comparison: the for loop takes 一个小的时间比较:for循环需要

Elapsed time is 0.688408 seconds.

while the bsxfun solution only takes bsxfun解决方案只需要

Elapsed time is 0.007884 seconds.

which is a nice speed-up of 87 for the exact same results. 对于完全相同的结果,这是一个很好的加速87。

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

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