MATLAB: How to Findthe permutation matrices that produce another matrix

matrixmatrix manipulationmatrix permutationpermutation

How to find a matlab code/command that will produce the permutation matrices of a matrix?
Let's consider the example below: I'm given the matrices A and B.
A=[1 2 3;4 5 6; 7 8 9] is a given matrix and B=[9 7 8;3 1 2; 6 4 5] is a permuted version of A.
My goal is to use Matlab to find the Matrices L (that pre-multiply A) and R(that post-multiply A) such that LAR=B.
A=[1 2 3;4 5 6; 7 8 9]
L=[0 0 1;1 0 0;0 1 0]
%L is an n by n (3 by 3) that re-order the rows a matrix when it pre-multiply that matrix
R=[0 1 0;0 0 1;1 0 0]
%R is an n by n that re-order the columns of a matrix
What's the code or command to find L and R when I know A and B?

Best Answer

Let the matrices A and B be n x n with B a permuted version of the rows and columns of A.
s = 1:n;
I = eye(n);
[~,a1] = sortrows(sort(A,2));
[~,b1] = sortrows(sort(B,2));
b1(b1) = s;
[~,a2] = sortrows(sort(A,1).');
[~,b2] = sortrows(sort(B,1).');
b2(b2) = s;
L = I(a1(b1),:);
R = I(:,a2(b2));
For this to work depends very much on B having resulted from a permutation of the rows of A and then a permutation of the columns of that (or vice versa.) Also no two rows of A can consist of the same set of elements in whatever order, and similarly for its columns.