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.
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 withend
. - 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
.
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
.
Examples
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
- 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 useend
to grow the array size and append other elements to the array. For example,X(end+1) = 5
increases the length ofX
by 1 and adds a new element to the end ofX
. - Although
end
is sometimes optional in a function file, use it for better code readability.
Extended Capabilities
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