Programming and Data Types

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:

• ``````A(I)
``````A{I}
``````A.field
``````

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

• ``````B = subsref(A,S)
``````

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 the string `':'`.

For instance, the expression

• ``````A(1:2,:)
``````

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

• ``````S.type = '()'
``````S.subs = {1:2,':'}
``````

Similarly, the expression

• ``````A{1:2}
``````

uses

• ``````S.type ='{}'
``````S.subs = {1:2}
``````

The expression

• ``````A.field
``````

calls `subsref(A,S)` where

• ``````S.type = '.'
``````S.subs = 'field'
``````

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

• ``````A(1,2).name(3:4)
``````

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

For an array index:

• ```switch S.type
case '()'
B = A(S.subs{:});
end
```

For a cell array:

• ```switch S.type
case '{}'
B = A(S.subs{:}); % A is a cell array
end
```

For a structure array:

• ```switch S.type
case '.'
switch S.subs
case '`field1`'
B = A.`field1`;
case '`field2`'
B = A.`field2`;
end
end
```

Examples of the subsref Method

See the following sections for examples of the `subsref` method:

 Indexed Reference Using subsref and subsasgn Handling Subscripted Assignment