Handles in Logical Expressions
Handle objects do not evaluate to logicaltrue
orfalse
. You must use the function that tests for the state of interest and returns a logical value.
If Handle Is Valid
Useisgraphics
to determine if a variable contains a valid graphics object handle. For example, supposehobj
is a variable in the workspace. Before operating on this variable, test its validity:
ifisgraphics(hobj)...end
You can also determine the type of object:
ifisgraphics(hobj,'figure')...% hobj is a figure handleend
If Result Is Empty
You cannot use empty objects directly in logical statements. Useisempty
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:
closeallhRoot = groot; hRoot.CurrentFigure
ans = 0x0 empty GraphicsPlaceholder array.
For example, to determine if there is a current figure by querying the rootCurrentFigure
property, use theisempty
function:
hRoot = groot;if~isempty(hRoot.CurrentFigure)...% There is a current figureend
Another case where code can encounter an empty object is when searching for handles. For example, suppose you set a figure’sTag
property to the character vector'myFigure'
and you usefindobj
to get the handle of this figure:
ifisempty(findobj('Tag','myFigure'))...% That figure was NOT foundend
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 ifh
is a handle to a particular figure that has a value ofmyFigure
for itsTag
property:
ifh == findobj('Tag','myFigure')...% h is correct figureend
If you want to determine if different objects are in the same state, useisequal
:
hLine1 = line; hLine2 = line; isequal(hLine1,hLine2)
ans = 1