Borrar filtros
Borrar filtros

Remove First Element of Array And Add Element to the End (FIFO array)

286 visualizaciones (últimos 30 días)
Hi I'm trying to modify an array so that I remove the first element of an array completely (ie decrease the size of the array). Then once I've done that I would like to add a new element (increase the size of the array).
For instance:
>>array = {1,2,3,4}
>>remove element 1
>> array = {2,3,4}
>>add element
>> array = {2,3,4,5}
What I'm really trying to do is create a sort of FIFO array. I've seen some other examples... but most of them don't delete the size of the array then increase it (just delete values). Is there an easy way to do this?

Respuesta aceptada

Star Strider
Star Strider el 14 de Jun. de 2016
One approach:
array = {1,2,3,4};
array = array(2:end)
array{end+1} = 5
  2 comentarios
Matthew Mellor
Matthew Mellor el 14 de Jun. de 2016
Editada: Matthew Mellor el 14 de Jun. de 2016
Thanks! I got this to work, but for my application it runs slowly. Does this work by copying the whole array? I'm also concerned with efficiency. :\
Star Strider
Star Strider el 14 de Jun. de 2016
My pleasure!
There is only one other way I can think of to do it:
new_elem = 5;
array = cat(2, array{2:end},new_elem);
That might be more efficient. It is one line shorter, and the MATLAB functions are generally optimised (certainly more than the code I usually write), so that may be faster.
It creates a double array, not a cell array, but you can convert it back into a cell array with the same properties as the original ‘array’ variable easily enough by enclosing the cat call in a mat2cell call:
array = mat2cell(cat(2, array{2:end},new_elem), 1, ones(size(array)));

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Types en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by