Azzera filtri
Azzera filtri

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

286 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Star Strider
Star Strider il 14 Giu 2016
One approach:
array = {1,2,3,4};
array = array(2:end)
array{end+1} = 5
  2 Commenti
Matthew Mellor
Matthew Mellor il 14 Giu 2016
Modificato: Matthew Mellor il 14 Giu 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 il 14 Giu 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)));

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by