matlabplotdrawnow

Drawnow on Matlab: It store the figure or store the variable?


May you please help me on a question on DRAWNOW in Matlab?

When we using drawnow in Matlab, what happens inside?

It stores the figure of the previous-graph, then plot the next-part-of-graph on the same figure?

OR it forgets the whole previous-graph and plot the actual-new-graph (with both previous and next-part)?

The both methods show the same effect: a dynamic graph. But I want to know exactly what happens inside.

Thank you!


Solution

  • drawnow makes sure that MATLAB stops doing whatever its doing and draws in the screen.

    If you do

    hold on
    for ii=1:1000
       plot(ii,rand(1)); % assume complicated maths here
    end
    

    MATLAB will run the code and send the plot calls to the graphics engine. However, MATLAB is too busy running the loop to be drawing, as the code has priority over the plot.

    If you do

    hold on
    for ii=1:1000
       plot(ii,rand(1));
       drawnow; % Take a break, draw everything that you must before continuing
    end
    

    Then, as the comment says, you temporarily stop the execution of the code, to draw everything in the graphics pipeline, and then continue executing the code.

    drawnow has no influence in the fact that the figure is stored or not, that is the job of hold on.

    If you are worried about redrawing the whole thing, then make sure you have a look at set and get methods for graphics. With them you can get the xdata, modify it, and set it again, by ensuring that the graphics engine does not redraw/recompute anything else.


    Documentation for the hold function:

    https://uk.mathworks.com/help/matlab/ref/hold.html