gcf repeatedly returns gui and not newly created figures
3 views (last 30 days)
Show older comments
Simon Aldworth
on 14 Nov 2018
Commented: Philip Borghesani
on 15 Nov 2018
Hi all,
I am using a GUIDE-created gui to run a Simulink model and part of the output is a series of figures. I am creating the figures in a loop and printing each one to file within the same loop, as follows:
foldname = char("pitch_bounce_plots " + datestr(now,'yyyy_mm_dd_HH_MM_SS'));
mkdir(foldname);
for k = 1:18
figure;
surface(X,Y,charvalues(:,:,k));
view(3);
xlabel(xstring);
ylabel(ystring);
zlabel(charlabels(k));
grid on;
flname = foldname + "\figure_" + string(get(gcf,'Number'));
print(flname,'-dpng');
end
Each of the 18 plots is presented to me on screen one at a time, each overlaying the last. And yet, in the folder I have 18 images of the gui! Presumably, gcf is not referring to what I consider to be the current figure. What is also slightly weird is that the first image has all grey buttons and the other 17 have the gui run button highlighted in blue.
How do I ensure that my print command prints the figure that is on top at the time?
Eventually, I may make all the plot figures invisible and only print them to file, but for now I would like to see them.
Regards,
Simon.
0 Comments
Accepted Answer
Guillaume
on 14 Nov 2018
How do I ensure that my print command prints the figure that is on top at the time?
Simple, don't rely on the current figure since as you've discovered the current figure may not be the one you expect. Instead explictly capture the figure handle of the figure you want to print when you create it:
for k = 1:18
hfig = figure; %capture figure handle. Doesn't matter what gcf is, hfig will always be the figure we created
%...
flname = foldname + "\figure_" + hfig.Number));
print(hfig, flname, '-dpng');
end
Since the current figure can change, it may also be safer if you ensure that all your plots were directed to the correct figure/axes, so:
for k = 1:18
hfig = figure;
hax = axes(hfig); %guaranteed to be in the correct figure
surface(hax, X,Y,charvalues(:,:,k)); %guaranteed to be in the correct axes
view(hax, 3);
xlabel(hax, xstring);
ylabel(hax, ystring);
zlabel(hax, charlabels(k));
grid(hax, 'on');
flname = foldname + "\figure_" + hfig.Number));
print(hfig, flname, '-dpng');
end
6 Comments
Walter Roberson
on 14 Nov 2018
Tools such as bode() often do not support providing axes or figure choice .
Philip Borghesani
on 15 Nov 2018
Yes, some of the older "full function" plotting tools create a new figure and don't return a handle. In this case I belive bodeplot was added to address those issues.
More Answers (1)
See Also
Categories
Find more on Printing and Saving 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!