Numerical integration (integral, trapz) in MATLAB - Time & Space Complexity
When we use numerical integration in MATLAB, we want to know how the time it takes changes as we use more points.
We ask: How does the work grow when the input size grows?
Analyze the time complexity of the following code snippet.
x = linspace(0, 10, n);
y = sin(x);
result = trapz(x, y);
This code calculates the integral of the sine function using the trapezoidal rule with n points.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Summing areas of trapezoids between points.
- How many times: The operation repeats once for each pair of points, about n-1 times.
As we increase the number of points n, the number of trapezoids to sum grows roughly the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 9 |
| 100 | 99 |
| 1000 | 999 |
Pattern observation: The work grows linearly as n grows.
Time Complexity: O(n)
This means the time to compute the integral grows in direct proportion to the number of points.
[X] Wrong: "Using more points will only add a tiny bit of time, so it's almost free."
[OK] Correct: Each extra point adds work because the trapezoidal sum must include it, so time grows steadily with points.
Understanding how numerical methods scale helps you explain efficiency clearly and shows you can think about real problems beyond just writing code.
"What if we used a method that doubles the points each step, how would the time complexity change?"