Programming Previous page   Next Page

Handling Subscripted Reference

The use of a subscript or field designator with an object on the right-hand side of an assignment statement is known as a subscripted reference. MATLAB calls a method named subsref in these situations.

Object subscripted references can be of three forms--an array index, a cell array index, and a structure field name:

Each of these results in a call by MATLAB to the subsref method in the class directory. MATLAB passes two arguments to subsref.

The first argument is the object being referenced. The second argument, S, is a structure array with two fields:

For instance, the expression

causes MATLAB to call subsref(A,S), where S is a 1-by-1 structure with

Similarly, the expression

uses

The expression

calls subsref(A,S) where

These simple calls are combined for more complicated subscripting expressions. In such cases, length(S) is the number of subscripting levels. For example,

calls subsref(A,S), where S is a 3-by-1 structure array with the values:

How to Write subsref

The subsref method must interpret the subscripting expressions passed in by MATLAB. A typical approach is to use the switch statement to determine the type of indexing used and to obtain the actual indices. The following three code fragments illustrate how to interpret the input arguments. In each case, the function must return the value B.

For an array index:

For a cell array:

For a structure array:

Examples of the subsref Method

See the following sections for examples of the subsref method:


Previous page  Indexed Reference Using subsref and subsasgn Handling Subscripted Assignment Next page

© 1994-2005 The MathWorks, Inc.