How to create a circular buffer in MATLAB for continuous measurements in the correct order

I read: How to create a buffer matrix in MATLAB for continuous measurements? , question. I wanted to know if it is possible to store the values ​​sequentially and not the other way around as in the question without resorting to fliplr (flip from left to right) after each iteration?

+2


source to share


4 answers


Front to back:

buffSize = 10;
circBuff = nan(1,buffSize);
for newest = 1:1000;
    circBuff = [circBuff(2:end) newest]
end

      

circBuff = 991 992 993 994 995 996 997 998 999 1000



Back to front:

buffSize = 10;
circBuff = nan(1,buffSize);
for newest = 1:1000;
    circBuff = [newest circBuff(1:end-1)]
end

      

circBuff = 1000 999 998 997 996 995 994 993 992 991

+4


source


buffSize = 10;
circBuff = nan(1,buffSize);
for newest = 1:1000;
    circBuff = [circBuff(2:end), newest]
   %circBuff = [newest circBuff(1:end-1)] %reverse direction

end

      



I tested this, it doesn't take noticeable time to run in MATLAB. The profiler did not find any code bottlenecks.

+1


source


I just uploaded my fast looping buffer solution to

http://www.mathworks.com/matlabcentral/fileexchange/47025-circvbuf-m

The main idea behind this circular buffer is constant and fast performance and avoiding copy operations when using the buffer in the program:

% create a circular vector buffer
    bufferSz = 1000;
    vectorLen= 7;
    cvbuf = circVBuf(int64(bufferSz),int64(vectorLen));

% fill buffer with 99 vectors
    vecs = zeros(99,vectorLen,'double');
    cvbuf.append(vecs);

% loop over lastly appended vectors of the circVBuf:
    new = cvbuf.new;
    lst = cvbuf.lst;
    for ix=new:lst
       vec(:) = cvbuf.raw(:,ix);
    end

% or direct array operation on lastly appended vectors in the buffer (no copy => fast)
    new = cvbuf.new;
    lst = cvbuf.lst;
    mean = mean(cvbuf.raw(3:7,new:lst));

      

Check the screenshot to see that this circular buffer has advantages if the buffer is large, but the size of the data to be added each time is small, since the performance of circVBuf does NOT depend on the size of the buffer compared to a simple copy of the buffer.

Double buffering ensures predictable add times based on data to add in any situation. In the future, this class will give you a yes or no double buffering choice - things will speed up if you don't need a guaranteed time. speedtest

+1


source


For those who want to create a Matrix buffer instead of an array (nx1 or 1xn matrix), the code can be changed to:

buffSize = 10;
 circBuff = nan(3,buffSize);
 for newest = 1:1000;
 circBuff = [circBuff(1,2:end) newest; circBuff(2,2:end) newest; circBuff(3,2:end) newest; ]
 end

      

: D

0


source







All Articles