简体   繁体   English

如何将给定矩阵每一行中的所有元素与给定向量的相应元素相乘,然后在MATLAB中求和?

[英]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.

相关问题 如何选择给定(非常大)矩阵的各个元素,看它们是否在特定范围内并在Matlab中更改它们? - How do I select individual elements of a given (very large) matrix, see if they are in a particular range and change them in Matlab? 将矩阵中的每一列与另一列中的对应行相乘,然后在Matlab中求和 - Multiply each column in a matrix by corresponding row in another and sum results in Matlab 如何在MATLAB中将向量中的每个元素乘以另一个向量中的所有元素 - How can I multiply each element in vector by all elements of another vector in MATLAB 对于 MATLAB 中的矩阵中的每一列,如何将每一列中的元素相乘? - How do I multiply the elements in each column, for every column in a matrix in MATLAB? Matlab-基于给定索引的向量元素的总和 - Matlab - Sum groups of elements of a vector based on given indices 对于给定的(0,1)向量,在Matlab中返回该矩阵每一行的所有(1,0)对的索引 - for a given (0,1) vector, return the indices of all the (1,0) pairs for each row of this matrix in matlab 在MATLAB中将列元素乘以相应矢量元素的简单方法? - Simple way to multiply column elements by corresponding vector elements in MATLAB? matlab在与索引矩阵相对应的向量中检索元素 - matlab retrieve elements in a vector corresponding to matrix of indexes 如何在Matlab中找到矩阵中一个向量的元素的索引? - How do I find the indices of the elements of one vector in a matrix in Matlab? 如何在matlab中做矩阵元素的和 - How to do sum of elements in matrix in matlab
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM