I have a fixed sized array in Matlab. When I want to insert a new element I do the following:
- To make room first array element will be overwritten
- Every other element will be shifted at new location
index-1---left shift. - 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.
13 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.
The circshift function is another solution:
B = circshift(A,shiftsize)circularly shifts the values in the array,A, byshiftsizeelements.shiftsizeis a vector of integer scalars where then-th element specifies the shift amount for then-th dimension of arrayA. If an element inshiftsizeis positive, the values ofAare shifted down (or to the right). If it is negative, the values ofAare 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]