Overload end for Classes
In a standard MATLAB® indexing expression, end returns the index value of the last element in the dimension in which
end appears. For example, in A(4,end), the
end 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.
ind = end(A,k,n)
Ais the object being indexed into.kis the dimension in the indexing expression whereendappears.nis the total number of indices in the expression.indis 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 the
end method with these arguments.
end(A,1,2)
Ais the object.k = 1becauseendappears in the first dimension of the indexing expression.n = 2because 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 syntax
ind = end(A,k,n). For example, the modular indexing class matlab.mixin.indexing.RedefinesParen has a built-in overload of
end.
function ind = end(obj,k,n) sz = size(obj); if k < n ind = sz(k); else ind = prod(sz(k:end)); end end
if-else statement calculates the return value based on where the
end appears in the indexing expression and whether the indexing
expression has values for all of the dimensions of the object array. For example, when
B is a 2-by-3-by-2 object array of a type that inherits from
RedefinesParen:k < n: Whenendis not the last value in the indexing expression, the overload returns the last value in that dimension. ForB(1,end,4),endreturns the size of the second dimension,3.k = n: Whenendis 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),endreturns2.If the indexing expression does not reference all the indices, then
prod(sz(k:end))returns the product of the size of dimensionkand the sizes of all unreferenced dimensions. For example, inB(1,end),endreturns the product of the sizes of the second and third dimensions,6.
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 expected
end behavior with an array.