Terminate block of code or indicate last array index
end also terminates a declared function. Although it is sometimes
end for better code readability.
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
If a file contains a function with one or more nested functions, then every
function in the file must be terminated with
If a script contains one or more local functions, then every function in the file
must be terminated with
end also represents the last index of an array. For example,
X(end) is the last element of
X(3:end) selects the third through final elements of
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
a = [0 0 1 1 0 0 0 1 0]; for k = 1:length(a) if a(k) == 0 a(k) = 2; end end
end to terminate a
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
average.m and save it in the current folder. Use
end to terminate the function.
function ave = average(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 = average(z)
ave = 50
Create a vector
X = 1:15;
Access the fifth through final elements of
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 = magic(3)
A = 3×3 8 1 6 3 5 7 4 9 2
B = A(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.
If an array
X already exists, you can use
to grow the array. For example,
X(end+1) = 5 increases the length of
X by 1 and adds a new element to the end of
end is sometimes optional in a function file, use it for
better code readability.
This function fully supports tall arrays. For more information, see Tall Arrays.
backgroundPoolor accelerate code with Parallel Computing Toolbox™
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
This function fully supports GPU arrays. For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
This function fully supports distributed arrays. For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).