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?
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With