Matlab - "seal" a figure so that plotting won't overwrite it, but will create a new figure automatically

figure, handle, matlab, matlab-figure, plot

Solution

Setting the property `NextPlot` of the current figure to `new` will create a new plot on the next call to `plot()`. Here's a small example:

plot(1:10, 1:10); % create a figure
set(gcf, 'NextPlot', 'new'); % next plot goes in new figure
plot(1:10, 1:10);

The `CurrentFigure` property you tried to change just stores the handle to the figure that has been used/focused most recently. Its value must be a valid figure handle. You could of course just create a new empty figure with `figure()` which automatically sets `CurrentFigure` to the handle of the newly created figure. But then you have two figure windows open. Therefore I think the above method is a little more elegant.

Problem

I'm writing a script that draws a figure. I'd like that figure to stay intact until it is closed by the user manually (e.g. clicking the cross). If the user issues a plotting command in Matlab prompt, this should not affect the existing figure, but should open a new figure automatically. How to block this default behaviour where Matlab reuses figure objects? This may also be important when using a figure as an interactive user interface, that should not be replaced with some other content when the user wishes to plot something. What I've tried: `help gcf` says that it retrieves the global `'CurrentFigure'` property. So, after plotting, I tried `set('CurrentFigure', 12345)`, hoping that it would reset the current figure to a nonexisting value (also tried zero, empty array). But that complains that it needs a handle. So I tried to instantiate a handle: `set('CurrentFigure', handle())`, but that complains that it's an abstract class. I guess I'm looking for a lightweight handle subclass that can be instantiated.

Original source