Matlab:寻找产生另一个矩阵的排列矩阵



我正在尝试编写MATLAB代码,它将允许我找到矩阵的排列矩阵。

让我们考虑下面的例子。我得到了矩阵AB:

A = [1 2 3;4 5 6; 7 8 9]   % is a given matrix
B = [9 7 8;3 1 2; 6 4 5]   % is a permuted version of A.

我的目标是找到矩阵L(预乘A)和R(后乘A),使得L*A*R = B:

% L is an n by n (3 by 3) that re-order the rows a matrix when it pre-multiply that matrix
L = [0 0 1;1 0 0;0 1 0] 
% R is an n by n that re-order the columns of a matrix
R = [0 1 0;0 0 1;1 0 0] 
B = L*A*R 

当我知道AB时,如何找到LR

要给出一个基线解决方案,这里是暴力方法:

function [L,R] = find_perms(A,B)
    [n,n] = size(A);
    p = perms(1:n);
    I = eye(n);
    for i=1:size(p,1)
        for j=1:size(p,1)
            L = I(p(i,:),:);
            R = I(:,p(j,:));
            if isequal(L*A*R, B)
                return;
            end
        end
    end
    % none found
    L = [];
    R = [];
end

让我们测试一下:

A = [1 2 3; 4 5 6; 7 8 9];
B = [9 7 8; 3 1 2; 6 4 5];
[L,R] = find_perms(A,B);
assert(isequal(L*A*R, B));

左/右排列矩阵如预期:

>> L
L =
     0     0     1
     1     0     0
     0     1     0
>> R
R =
     0     1     0
     0     0     1
     1     0     0

相关内容

最新更新