mesh and surf for surfaces in MATLAB - Time & Space Complexity
When we use mesh and surf in MATLAB, we create 3D surface plots from data grids.
We want to know how the time to draw these surfaces changes as the data size grows.
Analyze the time complexity of the following code snippet.
% Create grid points
[x, y] = meshgrid(linspace(-5,5,n), linspace(-5,5,n));
% Calculate surface values
z = sin(sqrt(x.^2 + y.^2));
% Plot surface
surf(x, y, z);
This code creates a grid of points, computes a surface height for each point, and then plots the surface.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Computing the surface values for each point in the grid.
- How many times: Once for each of the n x n points in the grid.
As the grid size n increases, the number of points grows by n squared, so the work grows quickly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 (10x10) |
| 100 | 10,000 (100x100) |
| 1000 | 1,000,000 (1000x1000) |
Pattern observation: Doubling n roughly quadruples the work because the grid is two-dimensional.
Time Complexity: O(n^2)
This means the time to compute and plot the surface grows with the square of the grid size.
[X] Wrong: "Increasing n only makes the code run a little slower because it's just one loop."
[OK] Correct: The code uses a grid with two dimensions, so the number of points grows by n times n, not just n.
Understanding how plotting time grows with data size helps you write efficient visualizations and explain performance clearly.
"What if we used a 3D grid (x, y, z) instead of 2D? How would the time complexity change?"