Skip to main content

Section 5.1 Anonymous functions

The concept of an anonymous function in Matlab closely corresponds to mathematical notion of a function: it consists of a formula that transforms input into output. For example, to have mathematical function \(f(x) = \exp(-x^2)\) in your code, you would write

f = @(x) exp(-x^2);

and then use f in expressions such as f(0) or 3*f(x-2).

When writing a function, one should consider whether it should accept input in the form of a vector or a matrix. The function in the previous paragraph works fine with scalar input, such as f(2) but throws an error if the input is a vector, for example f([0 1 2 3]). The reason is that with this input, x^2 becomes [0 1 2 3]^2 which is an error in Matlab where ^2 means matrix multiplication. We want an array operation, not a matrix product. Thus, the function should be written as

f = @(x) exp(-x.^2);

Then we can apply this function to a vector, for example to plot it.

x = linspace(-3, 3, 500);
plot(x, f(x))

An anonymous function can have multiple variables, for example the mathematical formula \(f(x, y, z) = (xy+1)/z\) could be defined as f = @(x,y,z) (x.*y + 1)./z. The inclusion of periods allows this function to vectors for its inputs, provided the vectors are of the same size.

The names of the parameters (variables inside of anonymous function) do not matter outside of that function. For example, there is no problem with the following code

f = @(x) x + 4;
x = 1;
y = 3;
disp(f(y))

The result is 7, because this is the output that f produces when its input is 3. The variable x outside of the function (which was given the value of 1) has no relation to the variable x inside of the function.

A limitation of anonymous functions is that they consist of a single expression: there is no place for conditional statements or loops. But one can still construct piecewise defined functions using inequalities as a part of an arithmetic expression. When an inequality such as (x < 3) appears in an expression, it is treated as 1 when the inequality is true, and 0 when false. Therefore, the function defined by

f = @(x) (x>=0).*sqrt(x) + (x < 0).*exp(x)

evaluates to \(\sqrt{x}\) when \(x\ge 0\) and to \(e^x\) when \(x \lt 0\text{.}\)

Write an anonymous function which, when given a number \(n\text{,}\) returns the sum of the reciprocals of all positive integers between \(1\) and \(n\text{.}\)

Answer
H = @(n) sum((1:n).^(-1));

These sums are called harmonic numbers (hence the letter H for this function). What happens if it is given a negative or fractional input? The regular vector 1:n contains all positive integers that are not greater than n. So, 1:3.7 is [1 2 3], same as 1:3. This means H(3.7) is 1/1 + 1/2 + 1/3, same as H(3). And if a number less than 1 is given, the regular vector 1:n is empty, and the sum of an empty set of numbers is 0. For example, H(-2) is 0.