[英]How to multiply each column of matrix A by each row of matrix B and sum resulting matrices in Matlab?
I have a problem which I hope can be easily solved. 我有一个问题,我希望可以轻松解决。 A is a N G matrix, B is N G matrix.
A是N G矩阵,B是N G矩阵。 The goal is to get matrix C
目标是获得矩阵C.
which is equal to multiplying each column of transposed A by each row of B and summing resulting matrices; 这等于将每列转置的A乘以B的每一行并求和得到的矩阵; total number of such matrices before summing is N N, their size is G G This can be easily done in MatLab with two for -loops:
求和之前这样的矩阵的总数是N N,它们的大小是G G。这可以在MatLab中用两个for -loops轻松完成:
N=5;
G=10;
A=rand(N,G);
B=rand(N,G);
C=zeros(G);
for n=1:1:N
for m=1:1:N
C=C+A(m,:)'*B(n,:);
end
end
However, for large matrices it is quite slow. 但是,对于大型矩阵,它非常慢。
So, my question is: is there a more efficient way for calculating C matrix in Matlab? 所以,我的问题是:在Matlab中有更有效的计算C矩阵的方法吗?
Thank you 谢谢
If you write it all out for two 3×3 matrices, you'll find that the operation basically equals this: 如果你把它全部写成两个3×3矩阵,你会发现操作基本上等于这个:
C = bsxfun(@times, sum(B), sum(A).');
Running each of the answers here for N=50
, G=100
and repeating each method 100 times: 在这里运行每个答案
N=50
, G=100
并重复每个方法100次:
Elapsed time is 13.839893 seconds. %// OP's original method
Elapsed time is 19.773445 seconds. %// Luis' method
Elapsed time is 0.306447 seconds. %// Robert's method
Elapsed time is 0.005036 seconds. %// Rody's method
(a factor of ≈ 4000 between the fastest and slowest method...) (最快和最慢的方法之间≈4000的因子......)
I think this should improve the performance significantly 我认为这应该会显着提高性能
C = zeros(G);
for n = 1:N
C = C + sum(A,1)'*B(n,:);
end
You avoid one loop, and should also avoid the problems of running out of memory. 您可以避免一个循环,并且还应该避免内存不足的问题。 According to my benchmarking, it's about 20 times faster than the approach with two loops.
根据我的基准测试,它比使用两个循环的方法快20倍。 (Note, I had to benchmark in Octace since I don't have MATLAB on this PC).
(注意,我必须在Octace中进行基准测试,因为我在这台PC上没有MATLAB)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.