在Matlab中,如何计算两个矩阵之间的快速外部积? [英] How to compute a fast outer product between two matrices, in Matlab?
本文介绍了在Matlab中,如何计算两个矩阵之间的快速外部积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个n×m矩阵,A
和B
.我想创建一个新的矩阵C
,类似于:
I have two n-by-m matrices, A
and B
. I want to create a new matrix C
which is something like:
for i = 1:n
C = C + outerProduct(A(i,:), B(i,:));
end
即C
是一个大小为m x m的矩阵,是A
和B
行的所有外部乘积之和.
i.e. C
is a matrix of size m x m, the sum of all outer products of the rows of A
and B
.
有没有for循环的快速方法(假设for循环在Matlab中非常慢)?
Is there a fast way to do it without a for loop (given that for loops are notoriously slow in Matlab)?
推荐答案
您正在执行的操作(行外部乘积的总和)等效于A
的转置版本与B
的乘积:
The operation you are performing (the sum of the row outer products) is equivalent to the multiplication of a transposed version of A
with B
:
C = A.'*B;
您可以使用以下示例查看此信息:
You can see this using the following example:
>> mat = magic(5); %# A sample 5-by-5 matrix
>> A = mat(1:4,:); %# Create a 4-by-5 matrix
>> B = mat(2:5,:); %# Create another 4-by-5 matrix
>> C = zeros(5); %# Initialize C to be 5-by-5
>> for i = 1:4, C = C + A(i,:).'*B(i,:); end; %'# Calculate C as you are now
>> isequal(C, A.'*B) %'# Test for equality with the shorter solution
ans =
1 %# Equal!
这篇关于在Matlab中,如何计算两个矩阵之间的快速外部积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文