Main Content

subsref

Indexed reference using function call

Description

B = subsref(A,S) returns the result from a parentheses, brace, or dot indexing expression, or a combination of one or more of those types, performed on the array A. The structure S contains the details of the indexing expression to be performed.

Note

Performing indexing by calling the subsref function explicitly is always slower than the equivalent indexing statement.

example

Examples

collapse all

Create a 5-by-5 array and display the first two rows using the standard indexing syntax.

A = magic(5);
B = A(1:2,:)
B = 2×5

    17    24     1     8    15
    23     5     7    14    16

Call subsref to perform the same operation. Use the substruct function to create the structure that describes the indexing expression.

C = subsref(A,substruct('()',{1:2,':'}))
C = 2×5

    17    24     1     8    15
    23     5     7    14    16

Create a 1-by-3 cell array and display the first two elements using the standard indexing syntax.

C = {"one",2,'three'};
[c1,c2] = C{1:2}
c1 = 
"one"
c2 = 
2

Call subsref to perform the same operation. Use the substruct function to create the structure that describes the indexing expression.

[d1,d2] = subsref(C,substruct('{}',{1:2}))
d1 = 
"one"
d2 = 
2

Create a structure with one field that has a vector value. Display the second element of the vector using the standard indexing syntax.

A.data = [5 10 15];
A.data(2)
ans = 
10

Call subsref to perform the same operation. Use the substruct function to create the structure that describes the indexing expression. The compound indexing expression includes a dot reference and a parentheses reference.

subsref(A,substruct(".","data","()",{2}))
ans = 
10

Input Arguments

collapse all

Target of indexing expression, specified as an array of any data type.

Indexing argument structure, also referred to as the substruct, specified as a structure array. Each structure has two fields:

  • type — Type of indexing operation, specified as "()", ".", or "{}" to indicate parentheses, dot, or brace indexing, respectively. The value can be a character vector or string scalar.

  • subs — Subscript values, specified as a character vector or string for dot indexing or a cell array of index vectors for parentheses or brace indexing.

S is a scalar structure for single indexing expressions, like A{1}, or a structure array for compound indexing expressions. For example, A{1}.field(3:5) has three levels of indexing. For this expression, S is a 1-by-3 structure array:

S(1)

type: '{}'

subs: {[1]}

S(2)

type: '.'

subs: 'field'

S(3)

type: '()'

subs: {[3 4 5]}

Data Types: struct

Tips

Extended Capabilities

expand all

Version History

Introduced before R2006a