146 percent Russian
146 percent Russian

Reputation: 2096

Why this multiplication is SO slow

I want to multiplicate 2 matrices. I need to multiplicate them element by element. Their size is 100x100 . But why this function works very slow? About 2-3 minutes.

for i=1:size(volumes,1)
  for j =1:size(volumes,2)
      ys(i,j) = volumes(i,j)*prices(i,j)

  end
end

How to speed up this operation?

Upvotes: 3

Views: 111

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25232

I think the major problem is, that you forgot the semicolon ; at the end of your line, where you do the calculation. So you are displaying the resulting 100x100 matrix ys 10000 times in your command window. That can take a looooot of time. (still 2-3min is even too much for that).

Also you should preallocate ys. Otherwise ys is growing in arraysize with every iteration, it can happen that the memory is not sufficient and the ys needs to be copied to a different location in memory, which also takes time. By pre-allocation you reserve space for the whole loop. You may find this answer interesting.

Therefore:

ys = zeros(size(volumes));
for i=1:size(volumes,1)
  for j =1:size(volumes,2)
      ys(i,j) = volumes(i,j)*prices(i,j);
  end
end

and it will work fine.


But apart from that use the elementwise-multiplication operator .*!

ys = volumes.*prices;

Upvotes: 7

Related Questions