[英]Multiply each row of a matrix by another matrix
Say I have the following matrix 说我有以下矩阵
B = [1 2 3;4 5 6;7 8 9;10 11 12]
and another matrix 和另一个矩阵
A = [a b c;d e f;g h i]
How do I multiply each row of matrix B by the matrix A (without using a for loop), ie 如何将矩阵B的每一行乘以矩阵A(不使用for循环),即
for i = 1:4
c(i) = B(i,:)*A*B(i,:)'
end
many thanks in advance. 提前谢谢了。
You can use: 您可以使用:
c = diag(B*A*B.');
However, this computes a whole 4×4 matrix only to extract its diagonal, so it's not very efficient. 但是,这仅计算整个4×4矩阵以提取对角线,因此效率不是很高。
A more efficient way that only computes the desired values is: 仅计算所需值的更有效方法是:
c = sum(bsxfun(@times, permute(sum(bsxfun(@times, B, permute(A, [3 1 2])), 2), [1 3 2]), B), 2);
Here is a breakdown of the above code: 以下是上述代码的细分:
c1 = sum(bsxfun(@times, B, permute(A, [3 1 2])), 2); % B(i,:)*A
c = sum(bsxfun(@times, permute(c1, [1 3 2]), B), 2); % (B(i,:)*A)*B(i,:)'
The first permute
is used so that the number of columns in B matches the number of columns in A . 使用第一个
permute
,以便B中的列数与A中的列数匹配。 Following the element-wise multiplication in bsxfun()
each row is summed up (remember, permute
shifted the rows into the 2nd-dimension), reproducing the effect of the vector-matrix multiplication B(i,:) * A occurring in the for
loop. 在
bsxfun()
按元素进行乘法运算之后,将每一行相加(请记住, permute
将行移至第二维),从而再现矢量矩阵乘法的效果B(i,:) * A在for
发生环。
Following the first sum
, the 2nd-dimension is a singleton dimension. 在第一个
sum
,第二维是单例维。 So, we use the second permute
to move the 2nd-dimension into the 3rd-dimension and produce a 2-D matrix. 因此,我们使用第二个
permute
将第二维移到第三维并生成一个二维矩阵。 Now, both c1 and B are the same size. 现在, c1和B的大小相同。 Following element-wise multiplication in the second
bsxfun()
each column is summed up (remember, permute
shifted columns back into the 2nd-dimension), reproducing the effect of B(i,:) * A * B(i,:)' . 在第二个
bsxfun()
中按元素进行乘法之后,将每一列相加(请记住,将移位的列permute
回第二维),从而重现B(i,:) * A * B(i,:)的效果 。
Take note of a hidden advantage in this approach. 注意这种方法的隐藏优势。 Since we are using element-wise multiplication to replicate the results of matrix multiplication, order of the arguments doesn't matter in the
bsxfun()
calls. 由于我们使用逐元素乘法来复制矩阵乘法的结果,因此参数的顺序在
bsxfun()
调用中bsxfun()
。 One less thing to worry about! 少一件事担心!
Or, from Matlab R2016b onwards, you can replace bsxfun(@times,...)
by .*
, thanks to implicit expansion : 或者,从Matlab R2016b开始,由于隐式扩展 ,您可以用
.*
替换bsxfun(@times,...)
.*
c = sum(permute(sum(B.*permute(A, [3 1 2]), 2), [1 3 2]).*B, 2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.