gpt4 book ai didi

algorithm - Matlab:找到产生另一个矩阵的置换矩阵

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:16 30 4
gpt4 key购买 nike

我正在尝试编写 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

关于algorithm - Matlab:找到产生另一个矩阵的置换矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36610281/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com