How can I get GCF to return a zero if there is no figure open in MATLAB 7.0 (R14)?

2 views (last 30 days)
I would like to have a dynamic method for generating and numbering figures. It would work very nicely if GCF returned zero when no figures are open so that:
figure(gcf+1)
would evaluate to figure(1) if no figures were open as opposed to figure(2) with an empty first figure and to the next figure if figures had already been created.
Can you tell me a versatile approach to accomplishing this objective using GCF written in its present form?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
GCF is not made to return zero because zero is the handle to the MATLAB root.
You can create a custom GCF function to return desired values. You can view the contents of the current GCF function by typing "edit gcf" at the MATLAB command prompt.
For example, if you replaced the last three lines in gcf.m with:
if isempty(h)
h = 0;
end
then the function would accomplish what you want.
However, if you used
figure(gcf)
with the edited function (or when GCF is used by other functions) you will obtain an error (if GCF returns 0, and you try to make a figure with handle equal to zero, you will obtain an error, since zero is already assigned to the root).
You might want to create your own file (e.g., mygcf.m), to avoid any conflicts.
Below is some sample code that creates five figure windows numbered 1 through 5, whether there is a figure window open or not.
number_of_figures = 5;
for i = 1:number_of_figures
% If figure does not exist, create a
% figure with that handle.
if ~ishandle(i)
figure(i);
else
figure(i);
end
end
Basically, this code is a loop based on the desired number of figures. If the figure already exists, a figure is not created and the loop moves to the next number. If the figure does not exist, then a new figure is created with the number.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!