subsref

Redefine subscripted reference for objects

Syntax

B = subsref(A,S)

Description

B = subsref(A,S) is called by MATLAB® for the syntax A(i), A{i}, or A.i when A is an object. S is a struct array with two fields, type and subs.

The type field is string containing '()', '{}', or '.', where '()' specifies integer subscripts, '{}' specifies cell array subscripts, and '.' specifies subscripted structure fields. The subs field is a cell array or a string containing the actual subscripts.

B is the result of the indexed expression.

MATLAB uses the built-in subsref function to interpret indexed references to objects. To modify the indexed reference behavior of objects, overload subsref in the class.

If A is a fundamental class (see Fundamental MATLAB Classes), then an indexed reference to A calls the built-in subsref function. It does not call a subsref method that you have overloaded for that class. Therefore, if A is an array of class double, and there is an @double/subsref method on your MATLAB path, the statement A(I) calls the MATLAB built-in subsref function.

Examples

See how MATLAB calls subsref for the expression:

A(1:2,:)

The syntax A(1:2,:) calls B = subsref(A,S) where S is a 1-by-1 structure with S.type='()' and S.subs={1:2,':'}. The string ':' indicates a colon used as a subscript.

See how MATLAB calls subsref for the expression:

A{1:2}

The syntax A{1:2} calls B = subsref(A,S) where S.type='{}' and S.subs={[1 2]}.

See how MATLAB calls subsref for the expression:

A.field

The syntax A.field calls B = subsref(A,S) where S.type='.' and S.subs='field'.

See how MATLAB calls subsref for the expression:

A(1,2).name(3:5)

Simple calls combine in a straightforward way for more complicated indexing expressions. In such cases, length(S) is the number of subscript levels. For instance, A(1,2).name(3:5) calls subsref(A,S) where S is a 3-by-1 structure array with the following values:

S(1).type='()'S(2).type='.'S(3).type='()'
S(1).subs={1,2}S(2).subs='name'S(3).subs={[3 4 5]}

More About

expand all

Tips

Within a class's own methods, MATLAB calls the built-in subsref, not the class defined subsref. This behavior enables to use the default subsref behavior when defining specialized indexing for your class. See subsref and subsasgn Within Class Methods — Built-In Called for more information.

Was this topic helpful?