3

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?

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
146 percent Russian
  • 2,016
  • 2
  • 14
  • 20
  • because it's an overkill. Just use `volumes.*prices`. Still, the loop shouldn't be that slow... – Robert Seifert May 28 '14 at 10:40
  • 4
    2-3 mins for elementwise-multiplication of 100x100 matrices? Pentium 1 or 2? – Divakar May 28 '14 at 10:40
  • 2-3mins for 10.000 Multiplications is to much. What kind of object are your matrices? Maybe their indexing operator does something expensive? – PMF May 28 '14 at 10:41
  • BTW, it is best [not to use `i` and `j` as variable names in Matlab](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab). – Shai May 28 '14 at 10:54

1 Answers1

7

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;
Community
  • 1
  • 1
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113