Reputation: 37
I am trying to reverse the elements of the matrix such that for given matrix order of the elements get reversed. my code is as shown for the 3x3 matrix is working.
X = [ 1 2 3 ; 4 5 6 ; 7 8 9 ];
B = [fliplr(X(3,:));fliplr(X(2,:));fliplr(X(1,:))];
input X =
1 2 3
4 5 6
7 8 9
output: B =
9 8 7
6 5 4
3 2 1
the above code I am trying to generalize for any matrix with the following code
[a,b]=size(X);
for i=0:a-1
A = [fliplr(X(a-i,:))];
end
but get only last row as output.
output A =
3 2 1
please help me to concatenate all the rows of the matrix one above to each other after it got reversed.
Upvotes: 0
Views: 676
Reputation: 60504
Your code doesn't work because you overwrite A
in every loop iteration. Instead, you should index into A to save each of your rows.
However, fliplr
can flip a whole matrix. You want to flip left/right and up/down:
B = flipud(fliplr(X));
This is the same as rotating the matrix (as Sardar posted while I was writing this):
B = rot90(X,2);
A totally different approach would work for arrays of any dimensionality:
X(:) = flipud(X(:));
Upvotes: 2
Reputation: 19689
rot90
is the function made for this purpose.
B = rot90(A,2);
Upvotes: 3