Using gcf in functions
조회 수: 29 (최근 30일)
이전 댓글 표시
I make plots in the main part of my scripts but I also do plotting from functions. It appears that when I call a function, gcf does not have to be passed as an argument, i.e., it appears as though gcf is some sort of global variable. I say "appears" because some times gcf doesn't seem to get updated and a plot from within a function will wipe out a previously generated figure from the main script. Can someone point me to some documentation that will clear this up for me?
Below is a sketch of the kind of thing I am trying to do. When I try passing gcf as an argument I still get inconsistent results.
% main part of script
t=0:100; y=sin(2*pi*t/20); figure(1); plot(t,y); dummy=RoutineThatDoesPlotting(t,y);
..... % end of script
function dummy=RoutineThatDoesPlotting(t,y); figure(gcf+1); plot(t,y); dummy=1; % end of function
Thanks for your help.
Dave
댓글 수: 0
채택된 답변
Image Analyst
2012년 2월 21일
gcf is basically the handle to the last figure window that you actued upon or brought up. It is the "current" one that things will happen in unless you specify otherwise. I don't think figure(gcf+1) is a wise idea though, because gcf won't always be an integer. It may have some weird handle number like 178.372, especially if it was created by running an app built with GUIDE. Just say fh = figure; instead, and that will create a figure and pick a handle number for it automatically rather than you trying to force it to use some particular number.
댓글 수: 0
추가 답변 (1개)
Jiro Doke
2012년 2월 21일
gcf is not a variable, but rather a function. So you don't need to treat it like an input argument to other functions. Whenever you call it, it will retrieve whichever is the current figure.
As for your issue, my advice is for you to not use gcf like that, i.e. gcf+1. Even though gcf may return a number, you shouldn't do any sort of arithmetic with it. If you just want to create a new figure (and not overwrite previous figures), just call figure with no input argument:
% main part of script
t=0:100;
y=sin(2*pi*t/20);
figure;
plot(t,y);
dummy = RoutineThatDoesPlotting(t,y);
..... % end of script
function dummy = RoutineThatDoesPlotting(t,y)
figure;
plot(t,y);
dummy=1;
% end of function
It's possible that your code doesn't work sometimes because your function RountineThatDoesPlotting is getting called too quickly before the system could update the "current figure". It could be just a timing thing; sometimes it works, sometimes it doesn't. That's another reason why you shouldn't use gcf that way.
참고 항목
카테고리
Help Center 및 File Exchange에서 Graphics Object Programming에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!