end - Terminate block of code or indicate last array index - MATLAB (original) (raw)

Terminate block of code or indicate last array index

Syntax

Description

end is a keyword that terminates for, while, switch, try, if, and parfor statements. Without anend statement, for, while,switch, try, if, andparfor wait for further input. Each instance ofend 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:

example

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

example

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

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)

Create a vector x.

Access the fifth through final elements of x.

ans = 1×11

 5     6     7     8     9    10    11    12    13    14    15

Access the odd-index elements of x.

ans = 1×8

 1     3     5     7     9    11    13    15

Access the last row of a matrix A using end.

A = 3×3

 8     1     6
 3     5     7
 4     9     2

Tips

Extended Capabilities

expand all

Theend function fully supports tall arrays. For more information, see Tall Arrays.

The end function fully supports GPU arrays. To run the function on a GPU, specify the input data as a gpuArray (Parallel Computing Toolbox). For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Version History

Introduced before R2006a