Matlab:找到产生另一个矩阵的置换矩阵
Matlab: Finding the permutation matrices that produce another matrix
我正在尝试编写 MATLAB 代码,使我能够找到矩阵的置换矩阵。
让我们考虑下面的例子。我得到了矩阵 A
和 B
:
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
(post-乘 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
当我知道 A
和 B
时如何找到 L
和 R
?
为了给出一个基线解决方案,这里是暴力法:
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));
left/right 置换矩阵符合预期:
>> L
L =
0 0 1
1 0 0
0 1 0
>> R
R =
0 1 0
0 0 1
1 0 0
我正在尝试编写 MATLAB 代码,使我能够找到矩阵的置换矩阵。
让我们考虑下面的例子。我得到了矩阵 A
和 B
:
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
(post-乘 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
当我知道 A
和 B
时如何找到 L
和 R
?
为了给出一个基线解决方案,这里是暴力法:
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));
left/right 置换矩阵符合预期:
>> L
L =
0 0 1
1 0 0
0 1 0
>> R
R =
0 1 0
0 0 1
1 0 0