Main Content

Handles in Logical Expressions

Handle objects do not evaluate to logical true or false. You must use the function that tests for the state of interest and returns a logical value.

If Handle Is Valid

Use isgraphics to determine if a variable contains a valid graphics object handle. For example, suppose hobj is a variable in the workspace. Before operating on this variable, test its validity:

if isgraphics(hobj)
   ...
end

You can also determine the type of object:

if isgraphics(hobj,'figure')
   ...% hobj is a figure handle
end

If Result Is Empty

You cannot use empty objects directly in logical statements. Use isempty to return a logical value that you can use in logical statements.

Some properties contain the handle to other objects. In cases where the other object does not exist, the property contains an empty object:

close all
hRoot = groot;
hRoot.CurrentFigure
ans = 

0x0 empty GraphicsPlaceholder array.

For example, to determine if there is a current figure by querying the root CurrentFigure property, use the isempty function:

hRoot = groot;
if ~isempty(hRoot.CurrentFigure)
   ... % There is a current figure
end

Another case where code can encounter an empty object is when searching for handles. For example, suppose you set a figure’s Tag property to the character vector 'myFigure' and you use findobj to get the handle of this figure:

if isempty(findobj('Tag','myFigure'))
   ... % That figure was NOT found
end

findobj returns an empty object if there is no match.

If Handles Are Equal

There are two states of being equal for handles:

  • Any two handles refer to the same object (test with ==).

  • The objects referred to by any two handles are the same class, and all properties have the same values (test with isequal).

Suppose you want to determine if h is a handle to a particular figure that has a value of myFigure for its Tag property:

if h == findobj('Tag','myFigure')
   ...% h is correct figure
end

If you want to determine if different objects are in the same state, use isequal:

hLine1 = line;
hLine2 = line;
isequal(hLine1,hLine2)
ans =

     1