Documentation Center

  • Trials
  • Product Updates

Accessing Object Handles

Introduction

MATLAB® assigns a handle to every graphics object it creates. All object creation functions optionally return the handle of the created object. If you want to access the object's properties (e.g., from a function or script), assign its handle to a variable at creation time to avoid searching for it later.

You can always obtain the handle of an existing object with the findobj function or by listing its parent's Children property.

See Searching for Objects by Property Values — findobj for examples.

See Protecting Figures and Axes for more information on how object handles are hidden from normal access.

Special Object Handles

The root object's handle is always zero. The handle of a figure is either:

  • An integer that, by default, is displayed in the window title bar

  • A floating point number requiring full MATLAB internal precision

The figure IntegerHandle property controls the type of handle the figure receives.

All other graphics object handles are floating-point numbers. You must maintain the full precision of these numbers when you reference handles. Rather than attempting to read handles off the screen and retype them, you must store the value in a variable and pass that variable whenever MATLAB requires a handle.

The Current Figure, Axes, and Object

An important concept in the Handle Graphics® technology is that of being current. The current figure is the window designated to receive graphics output. Likewise, the current axes is the target for commands that create axes children. The current object is the last graphics object created or clicked on by the mouse.

MATLAB stores the three handles corresponding to these objects in the ancestor's property list.

These properties enable you to obtain the handles of these key objects:

get(0,'CurrentFigure');
get(gcf,'CurrentAxes');
get(gcf,'CurrentObject');

The following commands are shorthand notation for the get statements:

Use these commands as input arguments to functions that require object handles. For example, you can click a line object and then use gco to specify the handle to the set command,

set(gco,'Marker','square')

or list the values of all current axes properties with

get(gca)

You can get the handles of all the graphic objects in the current axes (except those with hidden handles),

h = get(gca,'Children');

and then determine the types of the objects.

get(h,'type')
ans = 
      'text'
      'patch'
      'surface'
      'line'

While gcf and gca provide a simple means of obtaining the current figure and axes handles, they are less useful in code files. This is particularly true if your code is part of an application layered on MATLAB where you do not necessarily have knowledge of user actions that can change these values.

See Controlling Graphics Output for information on how to prevent users from accessing the handles of graphics objects that you want to protect.

Searching for Objects by Property Values — findobj

The findobj function provides a means to traverse the object hierarchy quickly and obtain the handles of objects having specific property values. To serve as a means of identification, all graphics objects have a Tag property that you can set to any string. You can then search for the specific property/value pair.

For example, suppose you create a checkbox that is sometimes inactivated in the GUI. By assigning a unique value for the Tag property, you can always find that particular instance and set its properties:

uicontrol('Style','checkbox','Tag','save option')

Use findobj to locate the object whose Tag property is set to 'save option' and disable it:

set(findobj('Tag','save option'),'Enable','off')

If you do not specify a starting object, findobj searches from the root object, finding all occurrences of the property name/property value combination that you specify.

Example — Finding Objects

This plot of the sine function contains text objects labeling particular values of the function.

Suppose you want to move the text string labeling the value sin(t) = .707 from its current location at [pi/4,sin(pi/4)], to the point [3*pi/4,sin(3*pi/4)] where the function has the same value (shown grayed out in the picture). To do this, determine the handle of the text object labeling that point and change its Position property.

To use findobj, pick a property value that uniquely identifies the object. This example uses the text String property:

text_handle = findobj('String','\leftarrowsin(t) = .707');

Move the object to the new position, defining the text Position in axes units.

set(text_handle,'Position',[3*pi/4,sin(3*pi/4),0])

findobj lets you restrict the search by specifying a starting point in the hierarchy, instead of beginning with the root object. This results in faster searches if there are many objects in the hierarchy. In the previous example, you know the text object of interest is in the current axes, so you can type

text_handle = findobj(gca,'String','\leftarrowsin(t) = .707');

Example — Using Logical Operators and Regular Expression

Suppose you create the following graph and want to modify certain properties of the objects created:

x = 0:30;
y = [1.5*cos(x);4*exp(-.1*x).*cos(x);exp(.05*x).*cos(x)]';
h = stem(x,y);
set(h(1),'Color','black',...
            'Marker','o',...
            'Tag','Decaying Exponential')
set(h(2),'Color','black',...
            'Marker','square',...
            'Tag','Growing Exponential')
set(h(3),'Color','black',...
            'Marker','*',...
            'Tag','Steady State')

The following instance diagram shows the graphics objects created in the graph. Each of the three sets of data produces a stemseries object, which in turn uses two lines to create the stem graph: one line for the stems and one for the markers that terminate each stem. There is also a line used for the baseline.

Controlling the Depth of the Search.  Make the baseline into a dashed line. Because it is parented directly to the axes, use the following statement to access only this line:

set(findobj(gca,'-depth',1,'Type','line'),'LineStyle','--')

By setting -depth to 1, findobj searches only the axes and its immediate children. As you can see from the above instance diagram, the baseline is the only line object parented directly to the axes.

Limiting the Search with Regular Expressions.  Increase the value of the MarkerSize property by 2 points on all stemseries objects that do not have their property Tag set to 'Steady State':

h = findobj('-regexp','Tag','^(?!Steady State$).');
set(h,{'MarkerSize'},num2cell(cell2mat(get(h,'MarkerSize'))+2))

See the regexp function for more information on using regular expressions in MATLAB.

Using Logical Operators.  Change the color of the stem lines, but not the stem markers. To do this, you must access the line objects contained by the three stemseries objects. You cannot just set the stemseries Color property because it sets both the line and marker colors.

Search for objects that are of Type line, have Marker set to none, and do not have LineStyle set to '--', which is the baseline:

h = findobj('type','line','Marker','none',...
   '-and','-not','LineStyle','--');
set(h,'Color','red')

The following picture shows the graph after making these changes.

Copying Objects

You can copy objects from one parent to another using the copyobj function. The new object differs from the original object only in the value of its Parent property and its handle; otherwise it is a clone of the original. You can copy a number of objects to a new parent, or one object to a number of new parents, as long as the result maintains the correct parent/child relationship.

When you copy an object having child objects, MATLAB copies all children as well.

Example — Copying Objects

Suppose you are plotting a variety of data and want to label the point having the x- and y-coordinates determined by 5π÷4,sin(5π÷4) in each plot. The text function allows you to specify the location of the label in the coordinates defined by the x- and y-axis limits, simplifying the process of locating the text:

text('String','\{5\pi\div4, sin(5\pi\div4)\}\rightarrow',...
     'Position',[5*pi/4,sin(5*pi/4),0],...
     'HorizontalAlignment','right')

In this statement, the text function:

  • Labels the data point with the string {5π÷4,sin(5π÷4)} using TeX commands to draw a right-facing arrow and mathematical symbols.

  • Specifies the Position in terms of the data being plotted.

  • Places the data point to the right of the text string by changing the HorizontalAlignment to right (the default is left).

To label the same point with the same string in another plot, copy the text using copyobj. Because the last statement did not save the handle to the text object, you can find it using findobj and the 'String' property:

text_handle = findobj('String',...
              '\{5\pi\div4,sin(5\pi\div4)\}\rightarrow');

After creating the next plot, add the label by copying it from the first plot:

copyobj(text_handle,gca).

This particular example takes advantage of the fact that text objects define their location in the axes data space. Therefore, the text Position property did not need to change from one plot to another.

Deleting Objects

You can remove a graphics object with the delete command, using the object's handle as an argument. For example, you can delete the current axes (and all of its descendants) with the statement

delete(gca)

You can use findobj to get the handle of a particular object you want to delete. For example, to find the handle of the dotted line in this multiline plot,

use findobj to locate the object whose LineStyle property is ':'

line_handle = findobj('LineStyle',':');

Use this handle with the delete command:

delete(line_handle)

You can combine these two statements, substituting the findobj statement for the handle:

delete(findobj('LineStyle',':'))
Was this topic helpful?