Efficiently compute a 3D matrix of outer products - MATLAB

前端 未结 3 1099
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 12:33

Suppose I have a matrix of elements like so:

A = reshape(1:25, 5, 5)

A =

 1     6    11    16    21
 2     7    12    17    22
 3     8    13    18    23
          


        
相关标签:
3条回答
  • 2020-11-29 12:57

    To state the obvious, have you tried a simple for-loop:

    [m,n] = size(A);
    B = zeros(m,m,n);
    for i=1:n
        B(:,:,i) = A(:,i) * A(:,i).';
    end
    

    You'll be surprised how competitively fast it is.

    0 讨论(0)
  • This is just a minor improvement over Divakar's answer. It is a little faster because it replaces a 3D-array permute with a 2D-array permute:

    B = bsxfun(@times, permute(A, [1 3 2]), permute(A, [3 1 2]));
    
    0 讨论(0)
  • 2020-11-29 13:15

    This -

    B = permute(bsxfun(@times,A,permute(A,[3 2 1])),[1 3 2])
    
    0 讨论(0)
提交回复
热议问题