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

3 views (last 30 days)
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

Accepted Answer

Nurahmed
Nurahmed on 24 Jun 2019
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

More Answers (1)

dpb
dpb on 23 Jun 2019
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.

Categories

Find more on Dates and Time in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!