matlab - 根据给定矩阵的对角线和反对角线创建新矩阵
问题描述
我想B
从 matrix创建矩阵A
,具有以下规则:
非对角元素
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 ];
我怎样才能创建B
给定的A
?
解决方案
您可以创建所有索引,然后它是一个单一的分配。
% 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
推荐阅读
- javascript - JQuery click 事件在第二次点击时触发,但不是在搜索表单中的第一次点击
- sql - 防止 XML 空标签解析为零
- c - 我的代码中的 SIGSEGV 错误在哪里以及如何纠正它?
- angular - 如何用角度的反应形式控制格式化输入?
- java - jHipster:8080 和 9000 端口上的不同版本
- reactjs - 使用 i18next 创建反应应用程序 - 从 json 文件加载翻译
- python - 在 Python 中替换文本文件中的字符串
- angular - `APP_INITIALIZER` - 由用户选择,可能吗?
- android - 如何在根 android 中读取 sysfs 目录?
- php - 如何在 laravel 中使用命令 LOCATE