How to move array elements to the left without using loops in Matlab?

I have a fixed size array in Matlab. When I want to insert a new item, I do the following:

  • To make the first element of the room array will be overwritten.
  • Each other element will be shifted to a new location index-1 --- left shift.
  • A new element will be inserted in the place of the last element, which becomes empty by moving the elements.

I would like to do this without using any loops.

+7
source share
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) ] 

This will add the variable (or array) newElem after the position of pos to array A

Let me know if this works for you!

[Edit] Well, it looks like you just want to use an array as a shift register. You can do it as follows:

 A = [ A(2:end) newElem ] 

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

+8
source

The circshift function is another solution:

B = circshift(A,shiftsize) cyclically shifts the values ​​in the array A , with shiftsize elements. shiftsize is a vector of integer scalars, where the n element determines the amount of shift for the n dimension of array A If the element in shiftsize positive, the values ​​of A shifted down (or to the right). If it is negative, the values ​​of A shifted (or to the left). If it is 0, the values ​​in this dimension are not shifted.

Example:

Move the first dimension values ​​down by 1 and 2 the dimension values ​​on 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 
+6
source

just delete the first value in the array and add a new one at the end.

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

Numerical example

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

Result: A having values ​​[2, 3, 4, 5]

+1
source

All Articles