Customize Object Indexing
Default Object Indexing
MATLAB® classes support object array indexing by default. Many class designs require no modification to this behavior.
Arrays enable you to reference and assign elements of the array using a subscripted notation. This notation specifies the indices of specific array elements. For example, suppose that you create two arrays of numbers (using
randi and concatenation).
Create a 3-by-4 array of integers from 1 through 9:
A = randi(9,3,4)
A = 4 8 5 7 4 2 6 3 7 5 7 7
Create a 1-by-3 array of the numbers 3, 6, 9:
B = [3 6 9];
Reference and assign elements of either array using index values in parentheses:
B(2) = A(3,4); B
B = 3 7 9
The MATLAB default behavior also works with user-defined objects. For example, create an array of objects of the same class:
for k=1:3 objArray(k) = MyClass; end
Referencing the second element in the object array,
objArray, returns the object constructed when
k = 2:
D = objArray(2); class(D)
ans = MyClass
You can assign an object to an array of objects of the same class, or an uninitialized variable:
newArray(3,4) = D;
Arrays of objects behave much like numeric arrays in MATLAB. You do not need to implement any special methods to provide standard array behavior with your class.
For general information about array indexing, see Array Indexing.
Customize Object Indexing With Modular Indexing Classes
Since R2021b. Recommended over Code Patterns for subsref and subsasgn Methods.
To modify indexing behavior for your class, inherit from one or more modular indexing mixin classes. Each class is responsible for one group of indexing operations:
Each class defines abstract methods that handle the details of each indexing operation the class defines. Implement these methods to perform the operations your design requires.
You can inherit from these classes independently. For example, you can customize only
parentheses indexing by inheriting only from
RedefinesParen. The dot and
brace indexing behaviors in that case are the default MATLAB behaviors.
You can also choose to customize just one or two levels of indexing and forward
additional operations to another MATLAB object. For example, you can author a class that customizes parentheses
RedefinesParen) but uses the default behavior for dot
See Customize Parentheses Indexing for an example of this behavior.