How can I shift the elements in a vector without losing the elements? just shift the order

조회 수: 4 (최근 30일)
If I have
A = [1,2,3,4,5,6,7,8,9,10];
I want specific consecutive number of elements (e.g. 6,7,8) to shift left or shift right n bits. Assume I know the number orders and elements in the array A. I also know how many numbers I want to shift.
I need, (e.g. shift left 2 bits)
B = [1,2,3,6,7,8,4,5,9,10];
Or (e.g. shift left 1 bit)
B = [1,2,3,4,6,7,8,5,9,10];
Or (e.g. shift right 2 bits)
B = [1,2,3,4,5,9,10,6,7,8];
Thanks
Nur

채택된 답변

Nurahmed
Nurahmed 2019년 6월 24일
I am new to Matlab, but after one day struggle, I finally found the solution to my problem. It was fun!
A=1:10;
startPos=4;
numMove=2;
shiftBit=3; % minus--moveLeft; positive--moveRight; zero--don'tMove
B = A;
B(startPos+shiftBit:startPos+shiftBit+numMove-1)=A(startPos:startPos+numMove-1);
if shiftBit<=0
oldNum = A(startPos+shiftBit:startPos-1);
B(startPos+shiftBit+numMove:startPos+numMove-1)=oldNum;
else
oldNum = A(startPos+numMove:startPos+numMove+shiftBit-1);
B(startPos:startPos+shiftBit-1)=oldNum;
end

추가 답변 (1개)

dpb
dpb 2019년 6월 23일
Sorta' inconsistent definition, but look at
>> A=1:10;
>> circshift(A(4:end-2),-2) % case 1
ans =
6 7 8 4 5
>>
>> circshift(A(6:end),2) % case 3
ans =
9 10 6 7 8
>>
Have to just decide what it means to "shift" -- the latter above is actually a circular shift of the elements within the total vector while the first is more like swapping positions of a lesser subset altho can be written with circshift but selecting proper subset of the overall vector and pre- or post-pending the remainders.
With only the examples but not the logic behind "why" the difference, it's your call as to how to decide what is what really want.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by