[MATLAB logo] Exploiting MATLAB's Data Structures

Solution #7 - Vectorized Set/Get

The get and set functions are vectorized so that when used with more than one handle all the property values can be retrieved or set in one operation. The expression

s = get(h)

returns a structure containing as fields the names of the properties for the given handles (which all must be the same type) and their associated values. The dual syntax

set(h,s)

sets all the properties at once.

The expression

val = get(h,{'prop1','prop2',...})

returns a cell array containing the specified property values for the given handles. The dual syntax

set(h,{'prop1','prop2',...},values)

is used to set the specified properties to the values in the values cell array.

You can use these expressions to vectorize operations on handle graphics objects.

Goal: Change all the text colors in an axis to their complements.

Key concepts: handles, vectorized set and get, structures, cell arrays

Key functions: set, get, findobj,

Solution

  1. Run sillytext
    sillytext
  2. Change all of the text colors to their complements. This means, change colors C to 1-C where C is a 1-by-3 rgb color value.
    h = findobj(gca,'type','text')
    C = get(h,{'color'})
    for i=1:length(C)
    C{i} = 1-C{i};
    end
    set(h,{'color'},C)
    The findobj call finds all the objects in the current axes that are text objects. We then get all the colors for the objects using the vectorized get. We then must run a for loop over the colors to convert them to their complements. Finally, we change all the colors to the new colors using a vectorized set operation.
  3. Alternate solution
    h = findobj(gca,'type','text')
    C = get(h,{'color'})
    C = 1 - cat(1,C{:});
    C = num2cell(C,2);
    set(h,{'color'},C)
    This is shorter but just pushes the for loop down into the m-file num2cell.

Copyright © 1997 The MathWorks, Inc.
clay@mathworks.com
$Revision$ $Date$