gcf repeatedly returns gui and not newly created figures

조회 수: 1(최근 30일)
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'));
for k = 1:18
grid on;
flname = foldname + "\figure_" + string(get(gcf,'Number'));
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.

채택된 답변

Guillaume 2018년 11월 14일
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');
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');
  댓글 수: 6
Philip Borghesani
Philip Borghesani 2018년 11월 15일
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.

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Simon Aldworth
Simon Aldworth 2018년 11월 15일
Apologies all. When I read the text following print(fig,_) I took onboard the words 'Simulink block diagram' and somehow missed the reference to 'figure'. I'm surprised that line isn't more prominent in the list of print syntax options.


Find more on Specifying Target for Graphics Output 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!

Translated by