Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply each column of a matrix by another matrix

I have a M x N matrix. I want to multiply each of the N columns by a M x M matrix. The following does this in a loop, but I have no idea how to vectorize it.

 u=repmat(sin(2*pi*f*t),[n 1]);
 W = rand(n);
 answer = size(u);
 for i=1:size(u,2)
   answer(:,i) = W*u(:,i);
 end
like image 306
mac389 Avatar asked Oct 01 '12 13:10

mac389


1 Answers

You simply need to multiply the two matrices:

answer = W*u;

Think about it: in every iteration of your loop you multiply a matrix by a vector. The result of that operation is a vector, which you save into your answer in column i. Matrix multiplication is a similar thing: you can understand it as multiplication of a matrix (W) by a set of vectors, which form your matrix u.

So your code is good, just remove the loop :)

like image 180
angainor Avatar answered Sep 22 '22 19:09

angainor