2.8. MATLAB Functions¶
Scripts as discussed in MATLAB Scripts are nice because they let us edit our code until we get it right and save it in files for future use. But we often need something more. We have used many functions that are part of MATLAB’s library of functions. Now, we need to write our own functions.
Functions have a private workspace, so there is less concern about name conflicts.
A function provides a simple way to invoke code multiple times. Functions allow common code to be called with different parameters or data, which is easier than replicating code.
Knowing when to divide a program into separate functions versus keeping the code together is somewhat of an art form, which is best perfected by practice. Two questions will help with the design decisions.
Does the code need to be executed more than once, especially with different values?
Does the code provide a specific task? If so, putting it in a function may help to draw attention to the task and thus improve the clarity of the program.
Functions may be placed inside a script file or in their own file. Functions inside a script may only be called within that script. Place a function in a file with the same name as the function to make it available to scripts and other functions you might develop.
2.8.1. Syntax of a Function¶
In MATLAB, a function’s returned value(s) are specified by their local variable name on the function definition line. The returned values are the values of those variables at the end of the function. If there is more than one return value, they are listed like a row vector.
Note
Create help text by inserting comments at the beginning of your function. Position the help text immediately below the function definition line (the line with the function keyword). In the help comments, we usually put the function’s name in capital letters, which causes the help command to display the function’s name with bold letters.
Here is the syntax for defining a function with one return value and two input arguments.
function outPut = my1stFunction(input1, input2)
% MY1STFUNCTION - Help documentation
{your code}
outPut = {<return value>};
end
This function has two return values and two input arguments.
function [outPut1, outPut2] = my2ndFunction(input1, input2)
% MY2NDFUNCTION - Help documentation
{your code}
outPut1 = {<one return value>};
outPut2 = {<another return value>};
end
Functions are either private or public. The code for private functions is in the same file as a script or another function, and is only run from within the file. Private functions may not be run directly from the Command Window. In contrast, public functions may be run from the Command Window or from scripts and functions contained in other files. Public functions have two important constraints.
A file can not contain more than one public function.
The function’s name must match the file’s name.
Note
Private functions are also called helper functions.
2.8.2. Calling a Function¶
[out1, out2] = my2ndFunction(in1, in2);
The values of the input arguments and outputs are copied to the called function. The variable names are independent. They may be the same name with no name-space conflict, or have entirely different names. The only important thing about the variables is their order in the list of arguments and return values.
- Self Quiz
(Select all that apply.) Which of the following are valid ways to call a function called
myFunction
that takes three input arguments and returns two output variables?[
out1, out2
]
= myFunction(in1, in2, in3)
out1 = myFunction(in1, in2, in3)
myFunction(in1, in2, in3)
[
~, out2
]
= myFunction(in1, in2, in3)
- Answer All of the syntaxes shown are valid. The function call
returns only outputs that are requested. If no outputs are requested, the function still runs and the first output is saved to
ans
. Outputs that are not needed may be replaced with a tilde (~
) character.
2.8.3. Example Function¶
Here is a short example function. Notice how the return value is set as the last value of the return variable at the end of the function. The function calculates the sum of a sequence of numbers according to the equation that Johann Carl Friedrich Gauss reportedly discovered when he was a young boy. His teacher wanted to keep the students busy with a tedious assignment, so the students were instructed to find the sum of the digits from 1 to 100. Gauss surprised the teacher by finding the answer very quickly. He recognized that pairs of numbers had the same sum. The sum of 1 and 100 is the same as 2 and 99, as is 3 and 98. In the sequence from 1 to 100, there are 50 such pairs. In this example, we generalize the equation to work with any sequence with consistent spacing between the numbers.
function ssum = sequenceSum(sequence)
% SEQUENCESUM - The sum of a sequence of numbers. The
% spacing between numbers in the sequence
% must be consistent.
start = sequence(1);
stop = sequence(end);
n = length(sequence);
if mod(n, 2) == 0 % n is even
ssum = n*(start+stop)/2;
else % n is odd
ssum = (n-1)*(start+stop)/2 + sequence(ceil(n/2));
end
end
We can verify the help information.
>> help sequenceSum
sequenceSum - The sum of a sequence of numbers. The
spacing between numbers in the sequence
must be consistent.
We can test the function from the Command Window. We use the sum
function to verify the results.
>> sequenceSum(1:100)
ans =
5050
>> sum(1:100)
ans =
5050
>> sequenceSum(50:3:100)
ans =
1258
>> sum(50:3:100)
ans =
1258
2.8.4. Function Handles¶
MATLAB has a shortcut way of expressing simple functions that can be
expressed with one single statement. In the following example, f
is
the name of the function handle. The argument(s) passed to the
function are inside the parentheses after the @
symbol. The two
primary applications of function handles are to create data points
according to an equation and to pass a function as an argument to
another function.
%% An example of a function handle
f = @(x) exp(-x) .* sin(x);
t = linspace(0, 3*pi);
plot(t, f(t));