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?
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
source to share
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.
source to share