필터 지우기
필터 지우기

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

조회 수: 286 (최근 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