Numerical integration helps us find the area under a curve when we can't solve it exactly. It uses simple math steps to get a close answer.
0
0
Numerical integration (integral, trapz) in MATLAB
Introduction
When you want to find the total distance traveled from speed data points.
When you have a curve but no exact formula to calculate the area under it.
When you want to estimate the total amount of something changing over time from measurements.
When you want to check the area under a graph made from experimental data.
When you want to solve integrals that are too hard or impossible to solve by hand.
Syntax
MATLAB
q = integral(fun, a, b) q = trapz(x, y)
integral calculates the integral of a function fun from a to b.
trapz uses the trapezoidal rule to approximate the integral from vectors x and y.
Examples
This calculates the integral of x squared from 0 to 1.
MATLAB
q = integral(@(x) x.^2, 0, 1)
This uses
trapz to estimate the integral of x squared from 0 to 1 using points.MATLAB
x = 0:0.1:1; y = x.^2; q = trapz(x, y);
Sample Program
This program calculates the integral of sin(x) from 0 to pi using both integral and trapz. It then prints both results to compare.
MATLAB
% Define the function f = @(x) sin(x); % Calculate integral from 0 to pi result_integral = integral(f, 0, pi); % Create points for trapz x = linspace(0, pi, 100); y = sin(x); result_trapz = trapz(x, y); % Display results fprintf('Integral result: %.6f\n', result_integral); fprintf('Trapz result: %.6f\n', result_trapz);
OutputSuccess
Important Notes
integral is more accurate for smooth functions and works with function handles.
trapz works well when you have discrete data points but may be less accurate.
Increasing the number of points in trapz usually improves accuracy.
Summary
Numerical integration finds areas under curves when exact math is hard.
integral works with functions and limits.
trapz works with data points using the trapezoidal rule.