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

后端 未结 3 820
情歌与酒
情歌与酒 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: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!
    

提交回复
热议问题