Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 268
Shan Avatar asked Apr 11 '11 19:04

Shan


2 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.

like image 59
AVH Avatar answered Oct 05 '22 14:10

AVH


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
like image 30
Chris A. Avatar answered Oct 05 '22 13:10

Chris A.