带矢量的3D矩阵乘法 [英] 3D Matrix multiplication with vector
问题描述
这让我有些困扰:
假设您有一个三层矩阵.
Suppose you have a matrix with three layers.
是否有一种简单的方法将此矩阵与三个元素的向量相乘,以便第一层(所有元素)与向量的第一个元素相乘,依此类推...
Is there a simple way to multiply this matrix with a vector of three elements so that the first layer (all elements) gets multiplied with the first element of the vector and so on...
现在我必须使用一个函数来做到这一点:
Now I have to use a function to do it like this:
function out=fun(matrix,vector)
out=matrix;
for k=1:3
out(:,:,k)=out(:,:,k)*vector(k);
end
是否有一种有效的方法可以在一行中完成此操作而无需使用功能?
Is there a efficient way to do this in just one line without the need for a function?
推荐答案
一个非常简洁的解决方案是重塑 vector
到1 x 1 x 3矩阵,并使用
One very terse solution is to reshape vector
into a 1-by-1-by-3 matrix and use the function BSXFUN to perform the element-wise multiplication (it will replicate dimensions as needed to match the sizes of the two input arguments):
newMatrix = bsxfun(@times,matrix,reshape(vector,[1 1 3]));
这篇关于带矢量的3D矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!