This is similar to @Nras answer, but faster and easier to read. I have several programs that do such things, and depending on how long your computing cycle is, updating your graphics can be a significant and annoying bottleneck.
If you know how long your vector will eventually end up, you can pre-select your plot and then update using the handle command:
n = 500; Fs = 1000; f1 = 10; t = 0; dt = 1 / Fs; s = nan(1,n); emptyvec = nan(1,n); h1 = plot(emptyvec,emptyvec,'-bo'); h2 = handle(line(emptyvec,emptyvec,'Color','r','Marker','x','LineStyle','--')); h1 = handle(h1); for i = 1 : n t = t + dt; s = sin(2 * pi * f1 * t); h1.XData(i) = t; h1.YData(i) = s; h2.XData(i) = t; h2.YData(i) = s^2; drawnow end
MATLAB ignores nan when calculating limits, so pre-allocating with nan makes xlim unnecessary. Also, pause not required when I run this. Your mileage may vary. I personally prefer to do something like this:
h = plot(t,emptyvec);
As long as t is famous and not crazy, it gives me an idea not only of how the calculation is performed, but also gives me a kind of progress bar. If it's crazy, I can fill t in chunks or use XData and YData as a loop buffer using ii = mod(i,100); as an index (for example), which will lead to an oscilloscope type effect. In addition, there is a time limit for constantly recalculating the axis limits.
If you don’t know how long your vector will be (if it is in a while , for example), you can either pre-pass the vector, which, as you know, will be longer, select it in pieces, or simply make a circular buffer object.
For multiple charts, preallocate uses the line function for each additional line. Unlike plot , you can simply transfer the more primitive line function to the handle function.
Please note: if you use MATLAB 2014b or more (I don’t), the new HG2 graphics system uses objects for descriptors rather than doubles, so the handle command, which converts a numerical descriptor to a handle object, is redundant, and the point designation can be used directly . Also note that handle used in this way undocumented