将矩阵的每一列乘以另一个矩阵 [英] Multiply each column of a matrix by another matrix
问题描述
我有一个M x N
矩阵.我想将每个N
列乘以M x M
矩阵.以下是循环执行的操作,但是我不知道如何对其进行矢量化处理.
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
推荐答案
您只需要将两个矩阵相乘即可.
You simply need to multiply the two matrices:
answer = W*u;
考虑一下:在循环的每次迭代中,都将矩阵乘以向量.该操作的结果是一个向量,您可以将其保存到第i列的答案中.矩阵乘法是类似的事情:您可以将其理解为矩阵(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 :)
这篇关于将矩阵的每一列乘以另一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!