Objects in Index Expressions
Objects as Indexes
MATLAB® can use objects as indices in indexed expressions. The rules of array indexing apply — indices must be positive integers. Therefore, MATLAB must be able to derive a value from the object that is a positive integer for use in the indexed expression.
Indexed expressions like X(A)
, where A
is an
object, cause MATLAB to call the subsindex
function. However, if an
indexing expression results in a call to an overloaded method from matlab.mixin.indexing.RedefinesParen
, matlab.mixin.indexing.RedefinesDot
, or matlab.mixin.indexing.RedefinesBrace
defined by class X
,
then MATLAB does not call subsindex
.
Ways to Implement Objects as Indices
There are several ways to implement indexing of one object by another object, X(A)
:
Define a
subsindex
method in the class ofA
that convertsA
to an integer. MATLAB callsA
'ssubsindex
method to perform indexing operations when the class ofX
does not overload methods frommatlab.mixin.indexing.RedefinesParen
,matlab.mixin.indexing.RedefinesDot
, ormatlab.mixin.indexing.RedefinesBrace
.If the class of
X
overloads methods fromRedefinesParen
,RedefinesDot
, orRedefinesBrace
these methods can call thesubsindex
method ofA
explicitly. The class ofA
must implement asubsindex
method that returns an appropriate value.
subsindex Implementation
subsindex
must return the value of the object as a zero-based integer index value in the range 0
to prod(size(X))-1
.
Suppose that you want to use object A
to index into object B
. B
can be a single object or an array, depending on the class designs.
C = B(A);
Here are two examples of subsindex
methods. The first assumes you can convert class A
to a uint8
. The second assumes class A
stores an index value in a property.
The
subsindex
method implemented by classA
can convert the object to numeric format to be used as an index:function ind = subsindex(obj) ind = uint8(obj); end
The class of
obj
implements auint8
method to provide the conversion from the object to an integer value.Class
A
implementssubsindex
to return a numeric value that is stored in a property:function ind = subsindex(obj) ind = obj.ElementIndex; end
Note
subsindex
values are 0-based, not 1-based.
See Also
matlab.mixin.indexing.RedefinesParen
| matlab.mixin.indexing.RedefinesDot
| matlab.mixin.indexing.RedefinesBrace