Number of arguments for customized indexing methods
returns
the number of expected inputs to n
= numArgumentsFromSubscript(obj
,s
,indexingContext
)subsasgn
or
the number of expected outputs from subsref
.
Overload numArgumentsFromSubscript
to describe the number of values to
return from indexing expressions that return or assign to a comma-separated list.
That is, indexing expressions that end in '{}'
or
'.'
indexing. The
numArgumentsFromSubscript
function can:
Access the indexing operations and indices used in the indexing expression.
Determine if an indexing operation is made in the context of a reference statement, an expression passed to a function, or an assignment.
If a class overloads numArgumentsFromSubscript
, MATLAB® calls
it to determine the number of array elements involved in an indexing
operation when the number of elements is greater than one. For example,
these '.'
indexing operations generate a call to numArgumentsFromSubscript
:
objArray.a
— Number of elements
referenced in a statement (Statement
)
func(objArray.a)
— Number
of elements returned in an expression (Expression
)
[objArray.a] = rhs
— Number
of values assigned with a comma-separated list (Assignment
)
MATLAB uses the calling context to determine when to apply
the value returned by numArgumentsFromSubscript
.
Your implementation of numArgumentsFromSubscript
can
provide different outputs for the three types of indexing statements.
For example, this overload of numArgumentsFromSubscript
:
Changes the expected number of output arguments from subsref
for
indexing expressions that are passed to functions.
Uses the indexing substructure s
to
determine the number of arguments required by the indexing operation
function n = numArgumentsFromSubscript(obj,s,indexingContext) if indexingContext == matlab.mixin.util.IndexingContext.Expression n = 1; else n = length(s(1).subs{:}); end end
Implement the subsref
method with a varargout
output to enable MATLAB to
call this method with the specified number of output arguments.
function varargout = subsref(obj,s) ... end
Overload numArgumentsFromSubscript
instead
of numel
to control the results
from overloaded subsref
and subsasgn
.
Overloading numArgumentsFromSubscript
can avoid
errors caused by overloading numel
.