Matlab 矩阵向量乘法
Matlab Matrix Vector multiplication
我是 Matlab 的新手,有一个简单的问题(对我来说不是那么简单):
我有一个矩阵 x:
x = 1 2 3
4 5 6
7 8 9
10 11 12
和向量 y:
y = 1 2 3
现在我想将数字 1 到 4 乘以 Vector 的第一个元素,将数字 5 到 8 乘以第二个元素,将数字 9 到 12 乘以最后一个元素。
找不到解决方案。非常感谢任何帮助!
谢谢保罗
如果您修改输入 x
以将所有 "groups" 设置为新输入的列,假设 xx
,例如为此 transposing and reshaping x
accordingly, you can use (element-wise) multiplication. MATLAB's implicit expansion allows such (element-wise) matrix operations. (Before MATLAB R2016b, one would need bsxfun
。)
这就是我的解决方案:
% Inputs
x = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
y = [1 2 3]
% Transpose and reshape x to set up all "groups" as new columns
xx = reshape(x.', 4, 3)
% (Element-wise) Multiplication using implicit expansion
z = xx .* y
输出:
x =
1 2 3
4 5 6
7 8 9
10 11 12
y =
1 2 3
xx =
1 5 9
2 6 10
3 7 11
4 8 12
z =
1 10 27
2 12 30
3 14 33
4 16 36
希望对您有所帮助!
我是 Matlab 的新手,有一个简单的问题(对我来说不是那么简单):
我有一个矩阵 x:
x = 1 2 3
4 5 6
7 8 9
10 11 12
和向量 y:
y = 1 2 3
现在我想将数字 1 到 4 乘以 Vector 的第一个元素,将数字 5 到 8 乘以第二个元素,将数字 9 到 12 乘以最后一个元素。
找不到解决方案。非常感谢任何帮助!
谢谢保罗
如果您修改输入 x
以将所有 "groups" 设置为新输入的列,假设 xx
,例如为此 transposing and reshaping x
accordingly, you can use (element-wise) multiplication. MATLAB's implicit expansion allows such (element-wise) matrix operations. (Before MATLAB R2016b, one would need bsxfun
。)
这就是我的解决方案:
% Inputs
x = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
y = [1 2 3]
% Transpose and reshape x to set up all "groups" as new columns
xx = reshape(x.', 4, 3)
% (Element-wise) Multiplication using implicit expansion
z = xx .* y
输出:
x =
1 2 3
4 5 6
7 8 9
10 11 12
y =
1 2 3
xx =
1 5 9
2 6 10
3 7 11
4 8 12
z =
1 10 27
2 12 30
3 14 33
4 16 36
希望对您有所帮助!