Main Content

end

Terminate block of code or indicate last array index

Syntax

end

Description

example

end is a keyword that 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 instance of end pairs with the closest previous unpaired for, while, switch, try, if, or parfor statement.

example

end also terminates a declared function. Although it is sometimes optional, use end for better code readability. end is required in these cases:

  • If a file contains functions, and one of the functions is terminated with end, then every function in the file must be terminated with end.

  • If a file contains a function with one or more nested functions, then every function in the file must be terminated with end.

  • If a script contains one or more local functions, then every function in the file must be terminated with end.

example

end also represents the last index of an array. For example, X(end) is the last element of X, and X(3:end) selects the third through final elements of X.

Examples

collapse all

Use end to close an if statement and a for loop. The first instance of end pairs with the if statement, and the second pairs with the for statement.

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

Use end to terminate a switch block.

choice = 1;

switch choice
    case 1
        disp('Vote for no. 1')
    case 2
        disp('Vote for no. 2')
    otherwise
        disp('Abstain')
end
Vote for no. 1

Declare a function in a file named calculateAverage.m and save it in the current folder. Use end to terminate the function.

function ave = calculateAverage(x)
    ave = sum(x(:))/numel(x); 
end

The function accepts an input array, calculates the average of its elements, and returns a scalar. Call the function from the command line.

z = 1:99;
ave = calculateAverage(z)
ave =

    50

Create a vector x.

x = 1:15;

Access the fifth through final elements of x.

x(5:end)
ans = 1×11

     5     6     7     8     9    10    11    12    13    14    15

Access the odd-index elements of x.

x(1:2:end)
ans = 1×8

     1     3     5     7     9    11    13    15

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,:)
B = 1×3

     4     9     2

Tips

  • Classes can overload the end function to implement specialized behavior. For more information, see Overload end for Classes.

  • If an array X already exists, you can use end to grow the array size and append other elements to the array. For example, X(end+1) = 5 increases the length of X by 1 and adds a new element to the end of X.

  • Although end is sometimes optional in a function file, use it for better code readability.

Extended Capabilities

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

Version History

Introduced before R2006a