How do I swap the elements in the major diagonal with those in the minor diagonal?

17 ビュー (過去 30 日間)
Brett Baxter
Brett Baxter 2020 年 9 月 22 日
編集済み: Stephen23 2020 年 9 月 23 日
So let's assume I have an array like so
x = 4x5 array
[1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2]
What I want to do is flip the diagonals of this matrix horizontally. So the end result would look like this,
x = [5 2 3 4 1
6 9 8 7 1
2 3 4 5 6
7 1 9 8 2]
As you can see, the diagonals starting from each corner going across have been flipped horizontally. 1 and 5 have swapped in the first row, 7 and 9 have swapped in the second row and so on. I tried indexing these values and then doing something like array(major) = array(minor) but this only brings back an error saying "Index exceeds the number of array elements. Could somebody help me?

採用された回答

madhan ravi
madhan ravi 2020 年 9 月 22 日
ix1 = find(eye(size(x)));
ix2 = sort(find(fliplr(eye(size(x)))), 'descend');
x([ix1, ix2]) = x([ix2, ix1])
  2 件のコメント
Stephen23
Stephen23 2020 年 9 月 23 日
編集済み: Stephen23 2020 年 9 月 23 日
+1 madhan ravi: neat idea, with effective use of linear indices.
madhan ravi
madhan ravi 2020 年 9 月 23 日
Thank you Stephen!

サインインしてコメントする。

その他の回答 (2 件)

Stephen23
Stephen23 2020 年 9 月 23 日
編集済み: Stephen23 2020 年 9 月 23 日
Similar to madhan ravi's answer, without sorting:
>> x = [1,2,3,4,5;6,7,8,9,1;2,3,4,5,6;7,8,9,1,2]
x =
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
>> ix0 = eye(size(x));
>> ix1 = flipud(find(ix0));
>> ix2 = find(fliplr(ix0));
>> x([ix1;ix2]) = x([ix2;ix1])
x =
5 2 3 4 1
6 9 8 7 1
2 3 4 5 6
7 1 9 8 2
Works for character matrices too:
>> x = char('A'+x)
x =
FCDEB
GJIHB
CDEFG
HBJIC
>> x([ix1;ix2]) = x([ix2;ix1])
x =
BCDEF
GHIJB
CDEFG
HIJBC

Bruno Luong
Bruno Luong 2020 年 9 月 22 日
x=[1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2]
s=size(x);
m=min(s);
n=s(2);
i=1:m;
id=sub2ind(s,i,i);
iad=sub2ind(s,i,n+1-i);
x([id iad])=x([iad id])

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by