Returning negative value of element in vector

10 views (last 30 days)
Hi!
I need to return every second element in a vector as negative, how do I do it?
for example; v=[1 4 -0.3 0.2 4 7 14 -25 -0.003 245]
should be vnew=[1 -4 -0.3 -0.2 4 -7 14 25 -0.003 -245]

Accepted Answer

Ameer Hamza
Ameer Hamza on 6 Nov 2020
Edited: Ameer Hamza on 6 Nov 2020
v=[1 4 -0.3 0.2 4 7 14 -25 -0.003 245];
v(2:2:end) = -v(2:2:end)
Result
>> v
v =
1.0000 -4.0000 -0.3000 -0.2000 4.0000 -7.0000 14.0000 25.0000 -0.0030 -245.0000
  2 Comments
Joel Bovin
Joel Bovin on 6 Nov 2020
Thank you! I read the indexing beforehand to try to solve it myself but I didn't understand it well enough, thank you for the help!

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!