Keep data from figures MATLAB

Viewed 42

I would like to keep data from figures using gcf. However, when I close the figure, I lose all the data stored into my variable.

map = randn(10,10);
figure; imagesc(map);
fig = gcf; % I have the data stored into fig
close all;
fig; % Error : handle to deleted Figure

How can I keep data from gcf even if the figure is closed.

1 Answers

You could save your figure as file using saveas before closing it. When you need it again, you can reload it with open.

Full example:

map = randn(10,10);
figure; imagesc(map);
fig = gcf;

%% Save figure in file 'MyFigureFile.fig'
saveas( fig, 'MyFigureFile', 'fig') 

close all;

%% Load figure from file 'MyFigureFile.fig'
open( 'MyFigureFile.fig' );


Other Option:

You could simply hide the figure instead of closing it using fig.Visible = false or fig.Visible = 'off' as suggested in Delete object handle and keep variable in MATLAB.

Related