Main Content

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)
  • A is the object being indexed into.

  • k is the dimension in the indexing expression where end 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 the end method with these arguments.

end(A,1,2)
  • A is the object.

  • k = 1 because end 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 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
The 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: When end is not the last value in the indexing expression, the overload returns the last value in that dimension. For B(1,end,4), end returns the size of the second dimension, 3.

  • k = n: When end 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 as sz(k). For example, in B(1,2,end), end returns 2.

    • If the indexing expression does not reference all the indices, then prod(sz(k:end)) returns the product of the size of dimension k and the sizes of all unreferenced dimensions. For example, in B(1,end), end returns 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.

Related Topics