Section 5.2 Named functions
Named functions can do the same thing as anonymous functions. Here is \(\exp(-x^2)\) again, this time as a named function.
function y = f(x) y = exp(-x.^2); end
But there may be multiple lines within the body of a named function, including loops and conditional statements. In general, it looks like this.
function y = myFunction(x) (do something); (do more things); (y = result of computations); end
A named functions can have multiple inputs: function w = myFunction(x, y, z)
. It can also have multiple outputs: function [u, v] = myFunction(x, y, z)
in which case both u
and v
must be assigned some values within the function.
Example 5.2.1. Arithmetic-geometric mean with given tolerance.
Write a named function with three inputs: numbers x, y
and tol
, which finds the arithmetic-geometric mean of a, b
with tolerance tol
(meaning that the process stops when the difference of arithmetic and geometric mean is less than tol
.)
function z = agm(x, y, tol) while abs(x - y) >= tol a = (x + y)/2; g = sqrt(x*y); x = a; y = g; end z = x; end
Note that the result has to be assigned to whichever function variable was designated as output on th first line of the function: in this case, z
. If you are familiar with Python, the following comparison may help:
def agm(x, y, tol): # some Python code computing z return zThe difference is that Matlab specifies the variable(s) to be returned at the beginning of the function, instead of at the end.
Example 5.2.1 illustrates an important point: a function has limited communication with the code outside of it. It receives input and produces certain output; nothing else that it does has any influence on the outside world. Suppose that the following sequence of commands was executed.
x = 0.3; y = 12; disp(agm(x, y, 1e-6)) disp(x) disp(a)
The third line will display the AGM which happens to be 3.7136. The fourth line will display the original value of x, which is 0.3
. Why is it still 0.3, even though the function agm
changed the value of x in the loop? This is because a function operates like a separate program with its own variables. The variable x inside of the function is its own local variable x, and changing it does not change x in other places. For the same reason, the last command disp(a)
produces an error: the variable a
is undefined. A variable with that name was introduces inside of function agm
but it does not exist outside of it.
One can have a function that does not return any values. Here is a function whose job is to plot the sine function on the interval \([a, b]\) using a given number of points.
function plotsin(a, b, num) x = linspace(a, b, num); plot(x, sin(x)) end
One can also have a function with no arguments (no input values). For example, this function computes an approximate value of the Golden Ratio by iterating \(\sqrt{x+1}\text{.}\)
function z = goldenratio() z = 1; for k = 1:100 z = sqrt(z+1); end end
One can use this function same as others: x = goldenratio();
or disp(goldenratio())
.
Back in the days when Matlab was designed, the convention was to put every named function in a separate “M-file” named as that function: for example, goldenratio.m
. Modern versions allow multiple named functions appear in the same file, along with code using those functions. However, one arbitrary restriction remains: “Function definitions in a script must appear at the end of the file.” For example, the following is allowed:
x = 0.3; y = 12; disp(agm(x, y, 1e-6)) function z = agm(x, y, tol) while abs(x - y) >= tol a = (x + y)/2; g = sqrt(x*y); x = a; y = g; end z = x; endbut moving the first three lines (top-level code) after the named function would result in an error.
Anonymous functions, described in Section 5.1, have no such restrictions.
Example 5.2.2. Smallest prime that is greater than a given number.
Write a function which, given a value n
, finds the smallest prime number that is greater than n
.
To determine whether some number k
is prime, use isprime(k)
. For example, while isprime(k)
is a loop that runs as long as k
stays prime. To have a loop that runs while k
is not prime, use while ~sprime(k)
. The character ~
means logical NOT in Matlab (recall that ~=
means “not equal”.)
function k = smallestprime(n) k = n + 1; while ~isprime(k) k = k + 1; end end
For example, smallestprime(31)
is 37, because the numbers 32, 33, 34, 35, 36 are not prime.