MATLAB: How to swap the elements in the major diagonal with those in the minor diagonal

arraydiagonalmatrix array

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?

Best Answer

ix1 = find(eye(size(x)));
ix2 = sort(find(fliplr(eye(size(x)))), 'descend');
x([ix1, ix2]) = x([ix2, ix1])