首页 > 解决方案 > 根据给定矩阵的对角线和反对角线创建新矩阵

问题描述

我想B从 matrix创建矩阵A,具有以下规则:

例如:

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 ];

我怎样才能创建B给定的A

标签: matlabmatrix

解决方案


您可以创建所有索引,然后它是一个单一的分配。

% 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

推荐阅读