3
$\begingroup$

I don't have enough memory to simply create diagonal matrix D x D, getting an 'out of memory' error. Instead of performing M x D x D operations in the first multiplication, I do M x D operations, but still my code takes ages to run.

Can anybody find a more effective way to multiply these matrices in matlab?

D=20000 M=25  A = floor(rand(D,M)*10); B = floor(rand(1,M)*10);   for i=1:D  for j=1:M   result(i,j) = A(i,j) * B(1,j);  end end   manual = result * A'; auto = A*diag(B)*A'; isequal(manual,auto) 
  • 0
    This was true of ancient versions, but these days matlab has a JIT compiler which is pretty good at optimizing loops. Vectorization doesn't actually provide much benefit, other than having cleaner code by expressing the problem at a higher level.2010-12-12

1 Answers 1

5

Your problem is discussed here. They suggest one of the following solutions:

A*bsxfun(@times,diag(D),A') 

OR

A*sparse(D)*A' 

Matlab is an interpreted language and so explicit loops are very slow (even though in the latest version there's supposedly in-place compilation). So everything must be vectorized.

As an aside, did you search the internet at all? It took Google 0.16s to come up with that web page as the first result (for matlab multiplying by a diagonal matrix).

  • 0
    it's very helpful, don't have much privile$g$es here, can't upvote, I can only accept the answer, which I usually do after I test it. Investigating all the intricacies now2010-12-12