Clear Filters
Clear Filters

Saving Specific Figure Handle For Recovery After Plotting Many Figures

29 views (last 30 days)
I'm writing quite a complicated simulation which involves multiple calls to different functions/subfunctions. The full setup has >100 switch cases, which usually all run and produce multiple plots. The overall intention is to get the code to switch to the 'best figure' (as set by some error metric we're minimising) once a function has finished running.
As a simple functioning piece of code which should cover my requirements whilst maintaining SOME simplicity, think of a structure something like this will suffice:
%Main Script
x = 0:0.01:10; Answers = function_1(x);
%% Function Files:
function Answers = function_1(x)
for methods = 1:2
switch methods
case 1; ph = 1; %Do Stuff
case 2; ph = 2; % Do Other Stuff
[Err,~] = function_2(x,ph); %%Take Results from Switches Make some other calculation and a PATCH plot
%*************************************************** Error Check Section - Save Axes/Figure No. Here from fun_2?
if Err(end) <= Err_min
Err_min = Err(end);
%Would Like to Save the figure handle here in a way such I can command line switch to that specific,
% most recent figure when there are a few 100 open.
Answers = Err;
%Additional Line Probably Needed Here To Switch To/Open The Figure Saved In The Error Check
%May include a save command here also..
function [Err,subresults] = function_2(x,ph)
y = x.*ph;
custom_plot_function(x,y); %Basically just a complicated ****patch object**** with titles & axes and markers & stuff in my actual code
subresults = x.^2 .*y;
Err = abs(y-subresults);
From the documentation, I think fig = gcf; ax = fig.CurrentAxes will get me the current axes handle, but I'm unsure how to use that handle to find the specific figure from the 100's generated, I have a feeling this is a simple syntax issue but I just can't find it in the documentation.

Accepted Answer

Matt J
Matt J on 3 Nov 2020
When you open a figure or axis you can save a handle to it, e.g.,
You can later use whichever h(i) you need to manipulate the figure.
Steven Lord
Steven Lord on 3 Nov 2020
If you have an axes handle, you can find the handle of the figure that contains it. You can even work your way back from an individual line to its containing figure.
f = figure;
ax = axes('Parent', f);
h = plot(ax, 1:10, 1:10);
ax2 = ancestor(h, 'axes'); % same as ax
ax2 == ax % true
f2 = ancestor(ax, 'figure'); % same as f
f2 == f % true
f3 = ancestor(h, 'figure'); % same as f and f2
f3 == f % true

Sign in to comment.

More Answers (0)


Find more on Graphics Object Programming in Help Center and File Exchange




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!