[英]How do I multiply all the elements in each row of a given matrix with corresponding elements of a given vector and sum them in MATLAB?
例如,给定矩阵randn(3,2)
-3行,2列和乘数randn(1,2))
2列的向量,我想获得一个大小为(3, 1)
的向量,其中每行将代表矩阵的行元素与给定的乘法器的每个元素相乘的总和
row_element_1*mul_element_1 + row_element_2*mul_element_2
Sounds like you want a matrix-vector multiplication. 听起来好像您想要矩阵向量乘法。
1> x = randn(3, 2)
x =
0.62055 -1.08060
-0.24064 -2.56097
-0.53202 -0.49712
2> y = randn(1, 2)
y =
-1.26010 -0.25200
3> x * y'
ans =
-0.50964
0.94860
0.79567
Note the transposition y'
. 注意换位y'
。
I think you can do this with a combination of bsxfun and sum, like so: 我认为您可以结合使用bsxfun和sum来做到这一点,如下所示:
a = rand(3,2);
b = rand(1,2);
result = sum(bsxfun(@times,a,b),2)
result =
0.333379034494579
0.613480382112731
0.093702948350719
Note dimension argument to SUM to sum along each row (rather than the default, which is down columns). 注意SUM的标注参数沿每一行求和(而不是默认值,即向下的列)。 BSXFUN applies a binary function with scalar expansion, which is ideal for the multiplication part here. BSXFUN应用带有标量扩展的二进制函数,在这里乘法部分是理想的。
A = randn(3, 2);
B = randn(1, 2);
C = A(:, 1) * B(1) + A(:, 2) * B(2); % size(C) = [3, 1]
If you have to scale to a much larger array with lots more columns and didn't want to write out the equation for C in full, you can use repmat
and element-wise multiplication 如果您必须缩放到具有更多列的更大数组并且不想完全写出C的方程式,则可以使用repmat
和逐元素乘法
A = randn(300, 200);
B = randn(1, 200);
C = sum(A .* repmat(B, 300, 1), 2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.