## end as Object Index

### Define `end` Indexing for an Object

When you use `end` in an object indexing expression, such as `A(4:end)`, the `end` function returns the index value corresponding to the last element in that dimension.

Classes can overload the `end` function to implement specialized behavior. If your class defines an `end` method, MATLAB® calls that method to determine how to interpret the expression.

The `end` method has the calling syntax:

```ind = end(A,k,n) ```

The arguments are described as follows:

• `A` is the object

• `k` is the index in the expression using the `end` syntax

• `n` is the total number of indices in the expression

• `ind` is the index value to use in the expression

For example, consider the 3-by-5 array `A`. When MATLAB encounters the expression:

```A(end-1,:) ```

MATLAB calls the `end` method defined for the object `A` using the arguments:

```ind = end(A,1,2) ```

These arguments mean that the `end` statement occurs in the first index and there are two indices. The `end` class method returns the index value for the last element of the first dimension (from which `1` is subtracted in this case). The original expression is evaluated as:

`A(3-1,:)`

If your class implements an `end` method, ensure that it returns a value appropriate for the class.

### The end Method

The `end` method for the `MyDataClass` example (see Class with Modified Indexing) operates on the contents of the `Data` property. The objective of this method is to return a value that can replace `end` in any indexing expression, such as:

```obj(4:end) obj.Data(2,3:end)```

This `end` method determines a positive integer value for `end`. The method returns the value so that MATLAB can use it in the indexing expression.

```function ind = end(obj,k,n) szd = size(obj.Data); if k < n ind = szd(k); else ind = prod(szd(k:end)); end end```