Main Content

Handles in Logical Expressions

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

If Handle Is Valid

Useisgraphicsto determine if a variable contains a valid graphics object handle. For example, supposehobjis 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. Useisemptyto 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 rootCurrentFigureproperty, use theisemptyfunction:

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’sTagproperty to the character vector'myFigure'and you usefindobjto get the handle of this figure:

ifisempty(findobj('Tag','myFigure'))...% That figure was NOT foundend

findobjreturns 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 withisequal).

Suppose you want to determine ifhis a handle to a particular figure that has a value ofmyFigurefor itsTagproperty:

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