Anonymous Functions

  1. A concise way to write a function
  2. A way to make a function remember some additional values
  3. Sometimes useful to adapt your function to be usable with in-built functions (yes, some functions take functions)

1. A concise way to write functions

In [1]:
% <function name> = @(<input1>, <input2>, ...) <one_output>
f = @(x, y) x^2 + y;
f(2.0, 0)
f(0, -1)

g = @() rand(); % don't have to have inputs
g()
ans =  4
ans = -1
ans =  0.024562

2. A way to make a function remember additional values

In [2]:
c = 2.0;
f = @(x) c * x;

f(3.0)
f(5.0)

c = -10.0 % doesn't matter if a change c, the function remembers the old version
f(3.0)

f = @(x) c * x;
f(3.0)
ans =  6
ans =  10
c = -10
ans =  6
ans = -30
In [3]:
f = @(x, c) c * x;
g = @(x) f(x, 2.0);

g(2.0)
ans =  4

3. Adapt your function to a format used by an in-built function

In [4]:
% polynomial coefficients: 3 * x^2 + 1 * x + -2
p = [3, 1, -2];
% use in-built polyval(polynomial_coefficients, x_argument) to evaluate a polynomial at x_argument
polyval(p, 0.0)
polyval(p, 1.0)

figure(1);
x = linspace(-5, 5, 1000);
plot(x, polyval(p, x));
ans = -2
ans =  2

The quad (use in Octave, in Matlab use integral), an example of a slight incompatibility.

$\texttt{quad(f, a, b)}$ integrates function $\texttt{f}$ from $\texttt{a}$ to $\texttt{b}$, but the function has to only take one argument, the x_argument (can be called whatever)

In [5]:
p = [3, 1, -2];
pol = @(t) polyval(p, x); % remember p
quad(pol, -5, 5)
ans =  680

Functions can return other functions

In [6]:
function output_fun = add_c(c)
    output_fun = @(x) x + c;
end
In [7]:
add_2 = add_c(2.0);
add_2(5.0)
add_2(-1)
ans =  7
ans =  1
In [8]:
add_234234 = add_c(234234);
add_234234(-234234)
ans = 0