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

531 次查看(过去 30 天)
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?

采纳的回答

Star Strider
Star Strider 2016-6-14
One approach:
array = {1,2,3,4};
array = array(2:end)
array{end+1} = 5
  2 个评论
Matthew Mellor
Matthew Mellor 2016-6-14
编辑:Matthew Mellor 2016-6-14
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 2016-6-14
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)));

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Types 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by