Overload end for Classes - MATLAB & Simulink (original) (raw)
Main Content
In a standard MATLABĀ® indexing expression, end returns the index value of the last element in the dimension in whichend
appears. For example, in A(4,end)
, theend
method returns the index of the last element in the second dimension of A
. You can overload end
in classes for specialized behavior.
Syntax and Default Behavior
This is the syntax MATLAB uses to call the end
method.
A
is the object being indexed into.k
is the dimension in the indexing expression whereend
appears.n
is the total number of indices in the expression.ind
is the index value to use in the expression.
Note
You cannot call the end
method directly using this syntax. MATLAB automatically calls the method when it encounters end in an indexing expression.
For example, A
is a 2-by-3 array of doubles. When MATLAB encounters the expression A(end,1)
, it calls theend
method with these arguments.
A
is the object.k = 1
becauseend
appears in the first dimension of the indexing expression.n = 2
because the expression has two indices.
The end
method returns 2
, which is the index of the last element in the first dimension of A
.
How RedefinesParen
Overloads end
Any overload of the end
method must have the calling syntaxind = end(A,k,n)
. For example, the modular indexing class matlab.mixin.indexing.RedefinesParen has a built-in overload ofend
.
function ind = end(obj,k,n) sz = size(obj); if k < n ind = sz(k); else ind = prod(sz(k:end)); end end
Theif-else
statement calculates the return value based on where theend
appears in the indexing expression and whether the indexing expression has values for all of the dimensions of the object array. For example, whenB
is a 2-by-3-by-2 object array of a type that inherits fromRedefinesParen
:
k < n
: Whenend
is not the last value in the indexing expression, the overload returns the last value in that dimension. ForB(1,end,4)
,end
returns the size of the second dimension,3
.k = n
: Whenend
is the last element in the indexing expression, the overload handles two cases:- If the indexing expression references all the indices, then
prod(sz(k:end))
gives the same result assz(k)
. For example, inB(1,2,end)
,end
returns2
. - If the indexing expression does not reference all the indices, then
prod(sz(k:end))
returns the product of the size of dimensionk
and the sizes of all unreferenced dimensions. For example, inB(1,end)
,end
returns the product of the sizes of the second and third dimensions,6
.
- If the indexing expression references all the indices, then
RedefinesParen
defines size
as an abstract method for the class author to implement, so the two methods are dependent on one another for the final behavior. See the Customize Parentheses Indexing example for a class that implements a size
method that provides the expectedend
behavior with an array.