Ron Bakker/MathLabHelp
Open MathLab ↗

Tutorial · Intermediate · 8 min

Writing your own functions

Short one-liners with @(x), longer functions with function … end, and how to pass them to integral, fzero and friends.

  1. One-line functions

    @(x) … makes a function you can store in a variable and call like any other.

    f = @(x) x.^2 .* exp(-x);
    f(2)
    fplot(f, [0 10])
    title('f(x) = x² e^(−x)')
    Try it ↗
  2. Functions in your script

    Longer functions use function output = name(inputs) … end. They can sit anywhere in the script and have their own variables.

    function a = ring_area(r_outer, r_inner)
      a = pi * (r_outer.^2 - r_inner.^2);
    end
    
    r = linspace(1, 3, 50);
    plot(r, ring_area(r, 1))
    xlabel('outer radius'), ylabel('area')
    Try it ↗
  3. Several outputs

    List outputs in square brackets, and ask for them the same way.

    function [m, s] = summary(x)
      m = mean(x);
      s = std(x);
    end
    
    [m, s] = summary([2 4 4 4 5 5 7 9])
    Try it ↗
    m = 5
    s = 2.1381
  4. Functions as inputs

    Numerical tools take functions: integral integrates, fzero finds roots, fminbnd finds a minimum.

    f = @(x) x.^2 .* exp(-x);
    area = integral(f, 0, Inf)
    peak = fminbnd(@(x) -f(x), 0, 10)
    cross = fzero(@(x) f(x) - 0.2, 0.5)
    Try it ↗
    area = 2
    peak = 2
    cross = 0.60527