与向量的 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×1×3 矩阵并使用函数 BSXFUN 执行逐元素乘法(它将根据需要复制维度以匹配两个输入参数的大小):
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屋!