How to compute a fast outer product between two matrices, in Matlab?

后端 未结 3 821
情歌与酒
情歌与酒 2021-01-07 02:27

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 +          


        
相关标签:
3条回答
  • 2021-01-07 03:10

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

    C = A*B';
    
    0 讨论(0)
  • 2021-01-07 03:26

    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.

    0 讨论(0)
  • 2021-01-07 03:33

    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!
    
    0 讨论(0)
提交回复
热议问题