Vectorize Double Loop - MATLAB

I have a double loop that 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 parform, and it worked. But I was looking for a more elegant solution. I tried and tried, but no luck ...

+4
source share
1 answer

Since you are performing only basic operations, like -, and .*it needs to be addressed with the help of bsxfun.

Use

bsxfun(@minus,P,S)

do an elementary subtraction P(k,1) - S(1,i). The output will be a matrix [2000,400]. You can apply the operation max(0,...)to this matrix and finally use it again bsxfunto multiply each row by the corresponding one r:

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

c [400,2000], , .

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

: for

Elapsed time is 0.688408 seconds.

bsxfun

Elapsed time is 0.007884 seconds.

87 .

+8

Source: https://habr.com/ru/post/1618695/


All Articles