move element in array

조회 수: 44 (최근 30일)
darksideofthemoon101
darksideofthemoon101 2012년 6월 19일
댓글: thiago rech 2020년 11월 13일
Hi,
I have an array of n elements, let's say for example:
[0 1 2 3 4 5]
I want to move the position of one of the elements left or right by one, let's say:
[0 1 2 4 3 5]
How can I do this? Does indexing help?
  댓글 수: 2
Stephen23
Stephen23 2017년 11월 17일
Just use indexing:
>> V = [0,1,2,3,4,5];
>> V([5,4]) = V([4,5])
V =
0 1 2 4 3 5
thiago rech
thiago rech 2020년 11월 13일
Wau! Thank you!

댓글을 달려면 로그인하십시오.

답변 (2개)

Navid Mohammadzadeh
Navid Mohammadzadeh 2017년 11월 17일
Why do not use "circshift" command?
Look: A =
1
2
3
4
5
6
7
8
9
10
Y = circshift(A,3)
Y =
8
9
10
1
2
3
4
5
6
7
  댓글 수: 2
Stephen23
Stephen23 2017년 11월 17일
편집: Stephen23 2017년 11월 17일
@Navid Mohammadzadeh: because circshift does not change the position of one element, as the example in the question shows.
thiago rech
thiago rech 2020년 11월 13일
Maybe that was not the answer he was looking for, but it helped me with something else really cool.
Thanks!

댓글을 달려면 로그인하십시오.


Christoph
Christoph 2012년 6월 19일
Hi,
your problem sounds wired. For what reason do you want to switch the postion of only two elements in an array?
Nevertheless I guess indexing is the only way to switch the positon of two elements. Also you need a temporary variable to store one of the objects. My solution would look like:
X = [1 2 3 4 5]; temp = X(3); X(3) = X(4); X(4) =temp;
If you need more than one time write an function with X and i (element you want to switch) as input argument and x as outputargument.
Kind regrads, CN
  댓글 수: 3
Christoph
Christoph 2012년 6월 19일
Hi Moon,
intresting idea. I'll try to write this function at the evening if the todays soccer game is not that interesting ;)
Christoph
Christoph 2012년 6월 19일
Just thought a further minute about your problem. I guess I would modelling mixing cards in a different way. I would divide the vector at a random position and put the first stack behind the second....that should look like this:
pos = randi([1, numberofcards-1])
stack = [stack(pos+1,end),stack(1:pos)];
put this it in a for loop and you modelled the perfect card mixer

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by