Gallery
Symbolic maths
4 examples. Open any of them in the editor to change it.
Derivatives and integrals, exactly Open ↗ Code
syms x
f = x^2*exp(-x)
df = diff(f, x) % product rule
F = int(f, x) % integration by parts
A = int(f, x, 0, Inf) % exact: 2
crit = solve(df == 0, x) % where the slope is zero
fplot(f, [0 8]), hold on
fplot(df, [0 8], '--')
fplot(F - subs(F, x, 0), [0 8], ':')
plot(double(crit), double(subs(f, x, crit)), 'ko'), hold off
legend('f(x) = x^2 e^{-x}', "f'(x)", 'area from 0', 'f''(x) = 0')
title(['f''(x) = ' char(df)])
Code
syms x y a b c
quadratic = solve(a*x^2 + b*x + c == 0, x) % the formula you learned at school
roots3 = solve(x^3 - 6*x^2 + 11*x - 6 == 0, x) % exact rational roots
S = solve([2*x + y == 7, x - 3*y == -7], [x, y]) % a linear system
% Where does the parabola meet the line?
p = x^2 - 2; l = x + 1;
xs = solve(p == l, x)
fplot(p, [-3 3]), hold on, fplot(l, [-3 3])
plot(double(xs), double(subs(l, x, xs)), 'ro', 'MarkerSize', 8), hold off
title(['x = ' char(xs(1)) ' and x = ' char(xs(2))])
Taylor series approximations Open ↗ Code
syms x
f = sin(x);
fplot(f, [-2*pi 2*pi], 'k', 'LineWidth', 2.5), hold on
for n = [2 4 6 8 10]
T = taylor(f, x, 0, 'Order', n);
fplot(T, [-2*pi 2*pi], 'LineWidth', 1.2)
end
hold off, ylim([-2 2])
legend('sin x', 'order 2', 'order 4', 'order 6', 'order 8', 'order 10')
title(char(taylor(f, x, 0, 'Order', 8)))
Projectile range: optimise by hand, symbolically Open ↗ Code
% Range of a projectile launched at speed v0 and angle theta (no air resistance)
syms v0 theta g t
x = v0*cos(theta)*t; y = v0*sin(theta)*t - g*t^2/2;
tflight = solve(y == 0, t); % two solutions: 0 and the landing time
R = simplify(subs(x, t, tflight(2))) % range
Rnum = subs(R, {v0, g}, {20, 9.81}); % 20 m/s on Earth
best = solve(diff(Rnum, theta) == 0, theta);
best = best(double(best) > 0 & double(best) < pi/2) % the best angle: pi/4
fplot(Rnum, [0 pi/2], 'LineWidth', 2)
xline(double(best), '--', '45°')
xlabel('launch angle (rad)'), ylabel('range (m)'), title(['R = ' char(R)])
fprintf('LaTeX: %s\n', latex(R))