This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Terminate block of code, or indicate last array index




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

end also marks the termination of a function. Although it is sometimes optional, use end for better code readability. If your function contains one or more nested functions, then you must terminate every function in the file, whether nested or not, with end. This includes primary, nested, private, and local functions.

If your script contains local functions, then you must terminate every local function in the file with end.

The end function also serves as the last index in an indexing expression. In that context, end is the same as size(X,k) when used as part of the kth index into array X. Examples of this use are X(3:end) to select the third through final elements of the array, and X(1,1:2:end-1) to select all even elements of the first row, excluding the last element. When using end to grow an array, as in X(end+1)=5, make sure X exists first.


collapse all

Use end to close a for loop and an if statement.

a = [0 0 1 1 0 0 0 1 0];
for k = 1:length(a)
    if a(k) == 0
        a(k) = 2;

Access the last row of a matrix A using end.

A = magic(3)
A = 3×3

     8     1     6
     3     5     7
     4     9     2

B = A(end,1:end)
B = 1×3

     4     9     2


  • Classes can overload the end function to implement specialized behavior. For more information, see end as Object Index.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

See Also

| | | | | | |

Introduced before R2006a