如何在Matlab中计算两个矩阵之间的快速外积?

发布于 2024-12-26 03:22:11 字数 306 浏览 2 评论 0原文

我有两个 n×m 矩阵,AB。我想创建一个新的矩阵 C ,它类似于:

for i = 1:n
    C = C + outerProduct(A(i,:), B(i,:));
end

C 是一个大小为 mxm 的矩阵,是 A 的行的所有外积的总和B

有没有一种无需 for 循环的快速方法(考虑到 for 循环在 Matlab 中非常慢)?

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

i.e. C is a matrix of size m x m, the sum of all outer products of the rows of A and B.

Is there a fast way to do it without a for loop (given that for loops are notoriously slow in Matlab)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

╰つ倒转 2025-01-02 03:22:11

您正在执行的操作(行外积之和)相当于 A 的转置版本与 B 的乘法:

C = A.'*B;

您可以使用以下示例查看这一点:

>> 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!

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!
栀梦 2025-01-02 03:22:11

您是否分析过您的 for 循环代码并发现它太慢了?如果没有,请在花费太多时间为循环损失而苦恼之前执行此操作。

您的 for 循环并不是特别糟糕,因为您只循环 n 次,但每个循环都执行 O(n*m) 工作。由于每次迭代都要做大量工作,因此循环惩罚不会那么严重。真正糟糕的情况是嵌套循环,例如,如果您也使用嵌套 for 循环计算外积。

Have you profiled your for loop code and found it to be too slow? If not, do it before you spend too much time agonizing over the loop penalty.

Your for loop is not particularly bad because you loop only n times but do O(n*m) work each loop. Since you're doing a lot of work each iteration, the loop penalty doesn't hit as hard. The really bad situations are nested loops, e.g. if you calculated the outer products with nested for loops too.

月棠 2025-01-02 03:22:11

也许我误解了,但我相信你正在寻找的是

C = A*B';

Perhaps I am misunderstanding, but I believe what you are looking for is

C = A*B';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文