I have a fixed sized array in Matlab. When I want to insert a new element I do the following:
index-1
---left shift. I would like to do it without using any loops.
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
, byshiftsize
elements.shiftsize
is a vector of integer scalars where then
-th element specifies the shift amount for then
-th dimension of arrayA
. If an element inshiftsize
is positive, the values ofA
are shifted down (or to the right). If it is negative, the values ofA
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.