Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. But I was looking for a more elegant solution. I have been trying and trying but no luck...

like image 314
phdstudent Avatar asked Feb 08 '23 09:02

phdstudent


1 Answers

As you are only doing element-wise operations, as -, and .*, this calls for a solution using bsxfun.

Use

bsxfun(@minus,P,S)

to do an element-wise subtraction P(k,1) - S(1,i). The output will be a [2000,400] matrix. You can apply the max(0,...) operation on this matrix, and finally use bsxfun again to multiplicate each row by the corresponding 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 = bsxfun(@times,max(bsxfun(@minus,P,S),0),r).';

A small time comparison: the for loop takes

Elapsed time is 0.688408 seconds.

while the bsxfun solution only takes

Elapsed time is 0.007884 seconds.

which is a nice speed-up of 87 for the exact same results.

like image 198
hbaderts Avatar answered Feb 15 '23 08:02

hbaderts