How to shift elements of an array to the left without using loops in matlab?

I have a fixed sized array in Matlab. When I want to insert a new element I do the following:

  1. To make room first array element will be overwritten
  2. Every other element will be shifted at new location index-1 ---left shift.
  3. The new element will be inserted at the place of last element which becomes empty by shifting the elements.

I would like to do it without using any loops.

1

3 Answers

I'm not sure I understand your question, but I think you mean this:

A = [ A(1:pos) newElem A((pos+1):end) ] 

That will insert the variable (or array) newElem after position pos in array A.

Let me know if that works for you!

[Edit] Ok, looks like you actually just want to use the array as a shift register. You can do it like this:

A = [ A(2:end) newElem ] 

This will take all elements from the 2nd to the last of A and added your newElem variable (or array) to the end.

2

The circshift function is another solution:

B = circshift(A,shiftsize) circularly shifts the values in the array, A, by shiftsize elements. shiftsize is a vector of integer scalars where the n-th element specifies the shift amount for the n-th dimension of array A. If an element in shiftsize is positive, the values of A are shifted down (or to the right). If it is negative, the values of A are shifted up (or to the left). If it is 0, the values in that dimension are not shifted.

Example:

Circularly shift first dimension values down by 1 and second dimension values to the left by 1.

A = [ 1 2 3;4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 B = circshift(A,[1 -1]); B = 8 9 7 2 3 1 5 6 4 

simply, remove the first value in the array and append the new one at the end.

A(1) = [] A = [A newValue] 

Numeric example

A = [1 2 3 4]; A(1) = []; A = [A 5]; 

The result is A having values [2, 3, 4, 5]

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like