how to shift specific elements in a array to a specific position?

조회 수: 18 (최근 30일)
Nurahmed
Nurahmed 2019년 6월 21일
답변: Nurahmed 2019년 6월 21일
I have an arry A = [1,2,3,4,5,6,7,8,9,10]. I want specific elements to shift the order but remain with the same elements. E.x. I want 3 elements (7,8,9) in A to shift 3 postions to the left to get an array B = [1,2,3,7,8,9,4,5,6,10]
Thanks,
Nur
  댓글 수: 1
Manali Gupta
Manali Gupta 2019년 6월 21일
Hi,
I assume that you know the index from which you need to shift.
Here,
a=1:10;
k=7;i=3;
b=[a(1:k-i-1) a(k:k+i-1) a(k-i:k-1) a(k+i:end )];

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

채택된 답변

obaldia
obaldia 2019년 6월 21일
Hello Nur!
Just shift the positions in the vector if you know the current position,
A = [1,2,3,4,5,6,7,8,9,10]
startPos = 7;
numElements = 3;
B = A;
oldElements = A(startPos-numElements:startPos-1);
B(startPos-numElements:startPos-1)=A(startPos:startPos+numElements-1);
B(startPos:startPos+numElements-1)=oldElements

추가 답변 (1개)

Nurahmed
Nurahmed 2019년 6월 21일
Hi,
Thanks a lot!

카테고리

Help CenterFile Exchange에서 LaTeX에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by