Efficient multiplication of super-size matrices in matlab

1k Views Asked by At

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

There are 1 best solutions below

3
On BEST ANSWER

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