Effacer les filtres
Effacer les filtres

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

286 vues (au cours des 30 derniers jours)
Matthew Mellor
Matthew Mellor le 14 Juin 2016
Commenté : Star Strider le 14 Juin 2016
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?

Réponse acceptée

Star Strider
Star Strider le 14 Juin 2016
One approach:
array = {1,2,3,4};
array = array(2:end)
array{end+1} = 5
  2 commentaires
Matthew Mellor
Matthew Mellor le 14 Juin 2016
Modifié(e) : Matthew Mellor le 14 Juin 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 le 14 Juin 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)));

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Types dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by