Reputation: 90475
Given an array:
array1 = [1 2 3];
I have to reverse it like so:
array1MirrorImage = [3 2 1];
So far I obtained this ugly solution:
array1MirrorImage = padarray(array1, [0 length(array1)], 'symmetric', 'pre');
array1MirrorImage = array1MirrorImage(1:length(array1));
Is there a prettier solution to this?
Upvotes: 21
Views: 58138
Reputation: 1
Use that man:%to array's mirror r=input('insert rows');c=('insert columns')b=size(x); r=b(1);c=b(2); a=0; y(r,c)=0; for i=1:r n=0; g=r-a; a=a+1; for j=1:c n=n+1;d(i,j)=x(g,n); end end disp(y)
Upvotes: -1
Reputation: 125854
UPDATE: In newer versions of MATLAB (R2013b and after) it is preferred to use the function flip
instead of flipdim
, which has the same calling syntax:
a = flip(a, 1); % Reverses elements in each column
a = flip(a, 2); % Reverses elements in each row
Tomas has the right answer. To add just a little, you can also use the more general flipdim
:
a = flipdim(a, 1); % Flips the rows of a
a = flipdim(a, 2); % Flips the columns of a
An additional little trick... if for whatever reason you have to flip BOTH dimensions of a 2-D array, you can either call flipdim
twice:
a = flipdim(flipdim(a, 1), 2);
or call rot90
:
a = rot90(a, 2); % Rotates matrix by 180 degrees
Upvotes: 31
Reputation: 60574
you can use
rowreverse = fliplr(row) % for a row vector (or each row of a 2D array)
colreverse = flipud(col) % for a column vector (or each column of a 2D array)
genreverse = x(end:-1:1) % for the general case of a 1D vector (either row or column)
http://www.eng-tips.com/viewthread.cfm?qid=149926&page=5
Upvotes: 14
Reputation: 12195
Another simple solution is
b = a(end:-1:1);
You can use this on a particular dimension, too.
b = a(:,end:-1:1); % Flip the columns of a
Upvotes: 20