contour plots in MATLAB - Time & Space Complexity
When we create contour plots in MATLAB, the program calculates many points to draw lines showing levels of a surface.
We want to understand how the time to draw these plots grows as the data size increases.
Analyze the time complexity of the following code snippet.
% Create grid points
[x, y] = meshgrid(linspace(-2, 2, n), linspace(-2, 2, n));
% Define function values on grid
z = x.^2 + y.^2;
% Draw contour plot
contour(x, y, z, 10);
This code creates a grid of points, computes values for each point, and draws contour lines for 10 levels.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calculating values for each point in the n-by-n grid.
- How many times: Once for each of the n² points.
As the grid size n grows, the number of points grows by n squared, so the work grows quickly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 |
| 100 | 10,000 |
| 1000 | 1,000,000 |
Pattern observation: Doubling n makes the work about four times bigger because we have n by n points.
Time Complexity: O(n^2)
This means the time to create the contour plot grows roughly with the square of the grid size.
[X] Wrong: "The time grows linearly with n because we just loop once over the data."
[OK] Correct: The data is a grid with n rows and n columns, so the total points are n times n, not just n.
Understanding how plotting time grows helps you explain performance when working with large data sets or visualizations.
"What if we increased the number of contour levels from 10 to 100? How would the time complexity change?"