Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


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);

manual = result * A';
auto = A*diag(B)*A';
share|cite|improve this question
You should ask this on Stackoverflow. Your code takes ages since you use loops and Matlab is interpreted. In Matlab everything must be vectorized. – Yuval Filmus Dec 12 '10 at 4:46
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. – Nick Alger Dec 12 '10 at 8:27
up vote 5 down vote accepted

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




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).

share|cite|improve this answer
thanks for that, Google's inverted indexes can't be beaten by anybody, it's 5am here, I'm just about to collapse – matcheek Dec 12 '10 at 4:54
@matcheek: If you believe Yuval's answer was helpful, it would be courteous of you to click the check mark on the left side of Yuval's answer. – J. M. Dec 12 '10 at 5:19
it's very helpful, don't have much privileges here, can't upvote, I can only accept the answer, which I usually do after I test it. Investigating all the intricacies now – matcheek Dec 12 '10 at 5:22

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.