(No difference)

Latest revision as of 12:00, 18 December 2008

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 =
Use the function fliplr(vector) to reverse a row vector quickly.
>> fliplr([1,2,3])
ans =
3 2 1

Alumni Liaison

Basic linear algebra uncovers and clarifies very important geometry and algebra.

Dr. Paul Garrett