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.
One-line functions
@(x) …makes a function you can store in a variable and call like any other.
Try it ↗f = @(x) x.^2 .* exp(-x); f(2) fplot(f, [0 10]) title('f(x) = x² e^(−x)')Functions in your script
Longer functions use
function output = name(inputs) … end. They can sit anywhere in the script and have their own variables.
Try it ↗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')Several outputs
List outputs in square brackets, and ask for them the same way.
Try it ↗function [m, s] = summary(x) m = mean(x); s = std(x); end [m, s] = summary([2 4 4 4 5 5 7 9])m = 5 s = 2.1381
Functions as inputs
Numerical tools take functions:
integralintegrates,fzerofinds roots,fminbndfinds a minimum.
Try it ↗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)area = 2 peak = 2 cross = 0.60527