[英]Multiply each column in a matrix by corresponding row in another and sum results in Matlab
Lets say I have matrices A = [1 2; 3 4], B = [4 3; 2 1]
可以说我有矩阵
A = [1 2; 3 4], B = [4 3; 2 1]
A = [1 2; 3 4], B = [4 3; 2 1]
A = [1 2; 3 4], B = [4 3; 2 1]
. A = [1 2; 3 4], B = [4 3; 2 1]
。 I want to multiply each column from matrix A ([1; 3], [2; 4])
by the corresponding row in matrix B ([4 3], [2 1])
and sum resulting matrices. 我想将矩阵
A ([1; 3], [2; 4])
的每一列乘以矩阵B ([4 3], [2 1])
的相应行,并对所得矩阵求和。 I have came up with the following code: 我想出了以下代码:
C = zeros(size(A));
for i = 1 : size(A, 1)
C = C + A(:, i) * B(i, :);
end
Could it be rewritten using some math trick or matlab function to get rid of the for loop? 可以使用一些数学技巧或Matlab函数重写它以摆脱for循环吗?
I see there is unclarity in my question regarding the result I want. 我看到我的问题对我想要的结果不明确。 The result should exactly mimic provided Matlab code, therefore I seek one matrix which is given by the matrix summation of the intermediate matrices that are created by multiplying each column vector with corresponding row vector from both matrices.
结果应该精确地模仿提供的Matlab代码,因此我寻求一个矩阵,该矩阵由中间矩阵的矩阵求和给出,该矩阵是通过将每个列向量与来自两个矩阵的对应行向量相乘而创建的。 For this specific example, it would be given by
对于此特定示例,将由
C = A(:, 1) * B(1, :) + A(:, 2) * B(2, :);
I am just looking for some generic, for-loop less version for any matrices of compatible dimensions. 我只是在寻找适用于任何兼容尺寸矩阵的通用,较少for循环的版本。
I just tried out my suggestion in the comments, and it seems to work with this octave tester : 我只是在评论中尝试了我的建议,并且似乎可以使用此八度测试仪 :
Short form (only works in Octave): 简短格式(仅适用于八度)
A = [1 2; 3 4], B = [4 3; 2 1]
X = sum((A * B)(:))
Long form (Matlab): 长格式(Matlab):
A = [1 2; 3 4]
B = [4 3; 2 1]
C = A * B % Stop here if you want the exact result from your Matlab code
x = sum(C(:)) % To get the sum of the resulting matrix
Sources: 资料来源:
Update, based on your update: 根据您的更新进行更新:
Output of A * B
: A * B
输出:
8 5
20 13
Output of your code: 您的代码输出:
8 5
20 13
You can also do this in MATLAB, to get the sum. 您也可以在MATLAB中执行此操作以获取总和。
C=ones(1,2)*A*B*ones(2,1)
The general form would be 一般形式为
C=ones(1,size(A,1))*(A*B)*ones(size(B,2),1);
EDIT 编辑
I see you updated your question for clarity. 我为清楚起见,看到您更新了问题。 The matrix product can be calculated directly
矩阵乘积可以直接计算
C = A*B;
as pointed out by jodag . 正如乔达格指出的。
This works provided you follow rules of linear algebra where inner dimensions of your matrices are the same (ie when number of columns in A match the number of rows in B; size(A,2)==size(B,1)
). 如果您遵循线性代数的规则,则矩阵的内部尺寸是相同的(即,当A中的列数与B中的行数匹配;
size(A,2)==size(B,1)
) size(A,2)==size(B,1)
该函数有效。
It appears that 看起来
C = zeros(size(A));
for i = 1 : size(A, 1)
C = C + A(:, i) * B(i, :);
end
is equivalent to the matrix multiplication 等价于矩阵乘法
C = A*B
for square matrices A
and B
. 用于平方矩阵
A
和B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.