Numerical Methods: Roots, Interpolation & Integration
Find roots of nonlinear equations, interpolate scattered data, and compute definite integrals.
Step 1 — Root finding with fzero
fzero(f, x0) finds a root of the scalar function f near the initial guess x0 using a combination of bisection and secant methods.
f = @(x) x^3 - 2*x - 5;
root = fzero(f, 2);
printf('Root: %.6f\n', root);
printf('f(root) = %.2e\n', f(root))▶ Run in SimLabExpected output: Root near 2.094551, f(root) ≈ 0
Step 2 — Interpolation with interp1
interp1(x, y, xq) interpolates a dataset at query points xq. Use the 'spline' method for smooth curves through the data points.
x = [0 1 2 3 4 5];
y = [0 0.8 0.9 0.1 -0.8 -1.0];
xq = linspace(0, 5, 200);
yq = interp1(x, y, xq, 'spline');
plot(x, y, 'o', xq, yq);
legend('Data', 'Spline');
title('Spline Interpolation')▶ Run in SimLabExpected output: Smooth spline curve passing through all data points
Step 3 — Numerical integration with quad
quad(f, a, b) computes ∫ₐᵇ f(x) dx using adaptive quadrature. Compare it with the known analytic result to verify accuracy.
f = @(x) sin(x);
I = quad(f, 0, pi);
printf('Numerical: %.6f\n', I);
printf('Analytic: %.6f\n', 2.0);
printf('Error: %.2e\n', abs(I - 2.0))▶ Run in SimLabExpected output: Numerical ≈ 2.000000, Error < 1e-10
Related Tutorials
Try SimLab — Free MATLAB® Alternative
466 functions. Runs in your browser. No install.
Open SimLab