Matrix/Tensor Triple Product?

前端 未结 3 1449
一个人的身影
一个人的身影 2021-01-04 23:47

An algorithm I\'m working on requires computing, in a couple places, a type of matrix triple product.

The operation takes three square matrices with identical dimens

3条回答
  •  甜味超标
    2021-01-05 00:41

    Let nxn be the matrix sizes. In Matlab, you can

    1. Group A and C into a n^2xn matrix AC, such that rows of AC correspond to all combinations of rows of A and C.
    2. Post-multiply AC by B. That gives the desired result, only in a different shape.
    3. Reshape and permute dimensions to get the result in the desired form.

    Code:

    AC = reshape(bsxfun(@times, permute(A, [1 3 2]), permute(C, [3 1 2])), n^2, n); % // 1
    X = permute(reshape((AC*B).', n, n, n), [2 1 3]);                               %'// 2, 3
    

    Check with a verbatim loop-based approach:

    %// Example data:
    n = 3;
    A = rand(n,n);
    B = rand(n,n);
    C = rand(n,n);
    
    %// Proposed approach:
    AC = reshape(bsxfun(@times, permute(A, [1 3 2]), permute(C, [3 1 2])), n^2, n);
    X = permute(reshape((AC*B).', n, n, n), [2 1 3]); %'
    
    %// Loop-based approach:
    Xloop = NaN(n,n,n); %// initiallize
    for ii = 1:n
        for jj = 1:n
            for kk = 1:n
                Xloop(ii,jj,kk) = sum(A(ii,:).*B(:,jj).'.*C(kk,:)); %'
            end
        end
    end
    
    %// Compute maximum relative difference:
    max(max(max(abs(X./Xloop-1))))
    
    ans =
        2.2204e-16
    

    The maximum relative difference is of the order of eps, so the result is correct to within numerical precision.

提交回复
热议问题