How can I get the first and last element to switch for a vector?

5 views (last 30 days)
If I am trying to use a code to use for any vector I put in my script, how could I get the first and last element to swap places while including the whole vector? For example, vec[-5 4 -4 6 8 -3] changes to [-3 4 -4 6 8 -5].
  2 Comments
Stephen23
Stephen23 on 4 Sep 2018
Edited: Stephen23 on 4 Sep 2018
How is this any different to the your earlier identical question and the identical answer?:
"I am using this code "vec([end,1])" but it is only showing -3 5."
What would you expect that to show? If you use indexing to retrieve the first and last values of an array, then that is what you will get: the first and last values.
michael story
michael story on 4 Sep 2018
I was asking to get the other elements in the vector to show in the command window. I figured it out with [vec(end),vec(2:end-1),vec(1)] but thanks for the help...

Sign in to comment.

Accepted Answer

Matt J
Matt J on 4 Sep 2018
Edited: Matt J on 4 Sep 2018
vec([1,end]) = vec([end,1])
  2 Comments
Stephen23
Stephen23 on 4 Sep 2018
Edited: Stephen23 on 4 Sep 2018
@michael story: in your question you use the variable name vec, and so that is exactly what Matt J and I used in our two identical answers to your two identical questions. Try changing your variable name vec into your other variable name switchVec, and seeing what happens:
switchVec([1,end]) = switchVec([end,1])
Neither Matt J nor I used the syntax that you used in your comment.
Matt J
Matt J on 4 Sep 2018
Edited: Matt J on 4 Sep 2018
@michael story: as opposed to making random guesses at Matlab syntax, I urge you to go back and refamiliarize yourself with the Getting Started documentation. You will find nothing there saying that assignment commands can return a value, as it might, say, in C/C++ and which you have assumed in
switchVec=([vec([1,end]) = vec([end,1])

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!