How can I only swap the first and last element of a vector?

7 views (last 30 days)
The vector I have is [-5 4 -4 6 8 -3], so how could I use a code/piece of script to get [-3 4 -4 6 8 -5]?

Accepted Answer

Stephen23
Stephen23 on 4 Sep 2018
Edited: Stephen23 on 4 Sep 2018
Simply in one line:
>> V = [-5,4,-4,6,8,-3];
>> V([end,1]) = V([1,end])
V =
-3 4 -4 6 8 -5
  3 Comments
Stephen23
Stephen23 on 4 Sep 2018
Edited: Stephen23 on 4 Sep 2018
Because you are not calling the syntax that I showed in my answer. When you call this:
V([1,end])
then it will simply the return that indices that you select. That is how indexing works, essentially by definition. You asked MATLAB for the first and last elements, so that is what it is giving you.

Sign in to comment.

More Answers (1)

KALYAN ACHARJYA
KALYAN ACHARJYA on 4 Sep 2018
Edited: KALYAN ACHARJYA on 4 Sep 2018
a=[-5 4 -4 6 8 -3];
b=a;
b(1)=a(length(a));
b(length(a))=a(1,1);

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!