Programming |

**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:

`S.type`

is a string containing`'()'`

, '`{}'`

, or`'.'`

specifying the subscript type. The parentheses represent a numeric array; the curly braces, a cell array; and the dot, a structure array.`S.subs`

is a cell array or string containing the actual subscripts. A colon used as a subscript is passed as a cell array containing the string`':'`

.

causes MATLAB to call `subsref(A,S)`

, where `S`

is a 1-by-1 structure with

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:

`S(1).type = '()' S(2).type = '.' S(3).type = '()'`

`S(1).subs = {1,2} S(2).subs = 'name' S(3).subs = {3:4}`

**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`

.

switch S.type case '.' switch S.subs case '

' B = A.*field1*

; case '*field1*

' B = A.*field2*

; end end*field2*

**Examples of the subsref Method**

See the following sections for examples of the `subsref`

method:

- The Polynom subsref Method
- The Asset subsref Method
- The Stock subsref Method
- The Portfolio subsref Method

Indexed Reference Using subsref and subsasgn | Handling Subscripted Assignment |

© 1994-2005 The MathWorks, Inc.