Practical 5: Function and Script M-files
Script M-file
Return statements
Return statements can be used to break the flow of execution of a function.
Example:
% indexOf: a function that finds the first index of a given number
% in an array. If the number is not in the array, the function
% outputs the index as -1.
% Inputs: a number, an array
% Outputs: an array index or -1 (means there is no such number in
% your input)
function position = indexOf(value, inputArray)
position = -1; % sets index to -1, number not yet found in array
for i = 1:length(inputArray)
i % this line shows how many times the for loop runs
if value == inputArray(i)
position = i;
return; % return stops the loop if the number is % found
end
end
Exercise: Using Return Statements > Put the indexOf.m M-file in your Current Directory. > Test it with the following commands in your Command Window: idx = indexOf(8, [1, -1, 1, 4]) idx = indexOf(8, [1, 1, 8, 1, 8]) i=2 xArray = [1, 2, 5, 7] idx = indexOf(i, xArray) > Disable the return statement by adding a comment sign, %. Re-test the function to see how many times the for- loop runs without it.
|
![]() |