How to detect if a figure exist?

조회 수: 108 (최근 30일)
John
John 2016년 1월 14일
댓글: Stephen23 2022년 11월 13일
To save the figure if one exists with:
saveas(gcf,figname);
the problem is that if no figure exists, it'll create a figure. How to detect if a figure exist before using above saveas command to avoid the creation of an empty figure?
Thanks.

채택된 답변

Brendan Hamm
Brendan Hamm 2016년 1월 14일
In 2014b and later you can query whether the Graphics Root objects has any children:
g = groot;
isempty(g.Children) % True if there are no open graphics objects, false otherwise
  댓글 수: 2
John
John 2016년 1월 14일
Thanks, I did this and it worked as well:
fig = get(groot,'CurrentFigure');
if ~isempty(fig)
filename=strcat(fname,'_',str,'.fig');
saveas(gcf,filename);
end
Roger Breton
Roger Breton 2022년 2월 8일
Thank you for sharing this tidbit of code!
It worked perfect for me in my script.
But I could not find "CurrentFigure' in the list of properties when I issued get(fig) from the command window in debuig mode?

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

추가 답변 (1개)

Stephen23
Stephen23 2016년 1월 14일
편집: Stephen23 2016년 1월 14일
The most reliable solution is to move your programming up a notch: use explicit handles and keep track of them.
While gcf and gca are fine for the command-line and playing with scripts, when you want to write more advanced functions then:
  • do not use gcf, gca.
  • store the handle of every axes, figure, and other relevant objects.
  • explicitly specify the parent of every object when it is created, plotted, etc.
When you code properly then your quest is trivial using ishghandle:
ishghandle(stored_handle)
  댓글 수: 2
Stanislav Ginzburg
Stanislav Ginzburg 2022년 11월 13일
Sometimes you may get handle on empty object plot([1,2], [NaN, NaN]); Result of ishghandle is true, Groot return handler of figure. And not empty too. The good practice is to prevent save empty objects.
Stephen23
Stephen23 2022년 11월 13일
"The good practice is to prevent save empty objects."
No, empty plots may also be information: it may be a perfectly valid and important result that for some figure nothing is plotted. This depends entirely on the specific situation and thus is the responsibility of the user to check.

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

카테고리

Help CenterFile Exchange에서 Printing and Saving에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by