MATLAB Answers

flip an array with the use of vectors

3 views (last 30 days)
I would like to flip specific cells in an array, not the whole array, with the use of vectors. For example a=[1 7 5 9 3 2 4 1] and i want to flip it from 5 to 2 and make it a=[1 7 2 3 9 5 4 1]. Any suggestions? Thank you in advance.

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 12 Jan 2020
Edited: Stephen Cobeldick on 12 Jan 2020
"Any suggestions?"
Use indexing (which in MATLAB starts from 1):
>> a = [1,7,5,9,3,2,4,1]
a =
1 7 5 9 3 2 4 1
>> a(3:6) = a(6:-1:3)
a =
1 7 2 3 9 5 4 1

  2 Comments

Zenia Askar
Zenia Askar on 16 Jan 2020
Hello again. Eventually, I choose from the array two numbers (not vectors) and I want to flip these cells instead. For example instead of 3rd and 6th cell, I have mumbers 5 and 2. How can i flip the array in this case? Thank you again.
Stephen Cobeldick
Stephen Cobeldick on 16 Jan 2020
>> a = [1,7,5,9,3,2,4,1]
a =
1 7 5 9 3 2 4 1
>> a([3,6]) = a([6,3])
a =
1 7 2 9 3 5 4 1

Sign in to comment.

More Answers (1)

Meg Noah
Meg Noah on 12 Jan 2020
a=[1 7 5 9 3 2 4 1];
a(3:6) = fliplr(a(3:6));

  0 Comments

Sign in to comment.

Sign in to answer this question.

Products