我想根据以下规则从矩阵 A
创建矩阵 B
:
非对角元素 A
类似于 B
的非对角元素。
A
的主对角线是B
A
的反对角线是B
的主对角线。
例如:
A = [ 1 2 3 4;
7 8 9 10;
13 14 15 16;
19 20 21 22 ];
B = [ 4 2 3 1;
7 9 8 10;
13 15 14 16;
22 20 21 19 ];
如何在给定 A
的情况下创建 B
?
最佳答案
您可以创建所有索引,然后这是一个单一的分配。
% Get size of square matrix A
n = size(A,1);
% Indicies are 1:n^2 by default
idx = 1:n^2;
% Swap diagonal and antidiagonal indices
idx( [1:(n+1):n^2, n^2-n+1:1-n:n] ) = [n^2-n+1:1-n:n, 1:(n+1):n^2];
% Use the indexing array to create B from A, reshape to be n*n
B = reshape( A( idx ), n, n );
示例 A
的输出:
B =
4 2 3 1
7 9 8 10
13 15 14 16
22 20 21 19
https://stackoverflow.com/questions/53869720/