Invert the vector in matlab? Why not y(5:1)=x(1:5)?

Status
Not open for further replies.

davyzhu

Advanced Member level 1
Joined
May 23, 2004
Messages
494
Helped
5
Reputation
10
Reaction score
2
Trophy points
1,298
Location
oriental
Activity points
4,436
matlab invert vector

How to invert the vector?

For example,
x=[1 2 3 4 5];
And I want y = [5 4 3 2 1];
But y(5:1)=x(1:5) seems cannot do that work.

Any suggestions will be appreciated!

Davy
 

matlab vektor invertieren

It is very simple.
If you have a matrix x=[1 2 3 4 5]; run the following script:

for i=1:size(x,2)
y(size(x,2)-i+1)=x(i);
end

and you will get the y you want. The function size() returns the size of the matrix x.
Regards
Flo
 

invert vector matlab

This is what you where trying to do.

x=[1 2 3 4 5];
y=x(5:-1:1)

You have to study how Matlab handles matrices and indexes. It
a little different from other standard methods.

Peace
 

matlab invert

about your question "Why not y(5,1)=x(1,5)?"
In Matlab y(m,n) means the element in the mth row and nth column.
i.e if you have this script
x=[1 2 3 4 5];
y(5,1)=x(1,5);

will give you a vector of one column and 5 rows
y=[0
0
0
0
5]
and it will assign all the remaining elements to zero as shown above.
I think that you will need a script as the one mentioned by gfloros.
or you can define it exlicitly
y=[5:-1:1] which means the starting element is 5 and the step is -1 till you reach the final element which is 1
Matlab is primarily based on Matrices and vectors, to get more help I think the Matlab getting started tutorial is the best refrence for that topic
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…