MATLAB Function Reference
end

Terminate `for`, `while`, `switch`, `try`, and `if` statements or indicate last index

Syntax

1. `while` `expression``            % `(or `if`, `for`, or `try`)

• ````   ``statements`
end
```

`B = A(index:end,index)`

Description

`end` is used to terminate `for`, `while`, `switch`, `try`, and `if` statements. Without an `end` statement, `for`, `while`, `switch`, `try`, and `if` wait for further input. Each `end` is paired with the closest previous unpaired `for`, `while`, `switch`, `try`, or `if` and serves to delimit its scope.

The `end` command also serves as the last index in an indexing expression. In that context, `end = (size(x,k))` when used as part of the `k`th index. Examples of this use are `X(3:end)` and `X(1,1:2:end-1)`. When using `end` to grow an array, as in `X(end+1)=5`, make sure `X` exists first.

You can overload the `end` statement for a user object by defining an `end` method for the object. The `end` method should have the calling sequence `end(obj,k,n)`, where `obj` is the user object, `k` is the index in the expression where the `end` syntax is used, and `n` is the total number of indices in the expression. For example, consider the expression

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

MATLAB will call the `end` method defined for `A` using the syntax

• ```end(A,1,2)
```

Examples

This example shows `end` used with the `for` and `if` statements.

• ```for k = 1:n
if a(k) == 0
a(k) = a(k) + 2;
end
end
```

In this example, `end` is used in an indexing expression.

• ```A = magic(5)

A =

17    24     1     8    15
23     5     7    14    16
4     6    13    20    22
10    12    19    21     3
11    18    25     2     9

B = A(end,2:end)

B =

18    25     2     9
```

`break`, `for`, `if`, `return`, `switch`, `try`, `while`