The Best Way

The best way to reverse a vector is probably as follows:

Say we have a vector,

test = [1,2,3,4,5]

and we want to reverse the numbers to provide us with a new vector:

newVector = [5,4,3,2,1]

To accomplish this without using a while loop or for loop, we can simply use the variable 'end', that is predefined in matlab:

newVector = test(end:-1:1)

What this statement say is take the last element of test ('end'), place that in the first element of newVector, then take the next last element of test ('end - 1') and put it into the second element of newVector, and so on, until newVector is a reversed copy of test. This method works with both row and column vectors.

Other Ways

Use the function flipud(vector) to reverse a column vector quickly.

>> flipud([1;2;3])
ans =
3
2
1
Use the function fliplr(vector) to reverse a row vector quickly.
>> fliplr([1,2,3])
ans =
3 2 1

Alumni Liaison

Ph.D. 2007, working on developing cool imaging technologies for digital cameras, camera phones, and video surveillance cameras.

Buyue Zhang