subsref

Reads through an index structure, the function behind A(i), A.f and A{i}.

Category: Programming > Classes

Syntax

B = subsref(A, S)

Returns the value selected by the index chain S.

Description

The interpreter turns every index expression into a call to subsref. Calling it yourself lets you index with a chain built at run time. Each element of S is applied to the result of the previous one, so substruct('()', {2}, '.', 'name') means A(2).name.

A class overloads subsref to control what obj(i), obj.name or obj{i} mean. Inside the overload, builtin('subsref', obj, S) falls back to the standard behavior.

Input arguments

A
The array, struct, cell array or object to index.
S
Structure array with fields type ('()', '{}' or '.') and subs, usually built with substruct.

Output arguments

B
The selected value; with a {} index on a cell array the output is the contents.

Example

Three kinds of index

M = magic(4);
subsref(M, substruct('()', {2, ':'}))
S.a = [1 2 3];
subsref(S, substruct('.', 'a', '()', {2}))
c = {1, 'two', [3 4 5]};
subsref(c, substruct('{}', {3}, '()', {2}))
Output
ans = 1×4

     5    11    10     8
ans = 2
ans = 4

See also

subsasgn substruct numArgumentsFromSubscript getfield