Multiply each column of a matrix by another matrix

2019-06-17 13:03发布

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

1条回答
啃猪蹄的小仙女
2楼-- · 2019-06-17 13:25

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

查看更多
登录 后发表回答