Axis control and formatting in MATLAB - Time & Space Complexity
When we control and format axes in MATLAB plots, some commands run repeatedly depending on the data size.
We want to know how the time to set axis properties grows as the data or plot size increases.
Analyze the time complexity of the following MATLAB code snippet.
x = 1:n;
y = rand(1, n);
plot(x, y);
axis([0 n 0 1]);
set(gca, 'XTick', linspace(0, n, 11));
set(gca, 'YTick', 0:0.1:1);
xlabel('X Axis');
ylabel('Y Axis');
title('Sample Plot');
This code plots n points and sets axis limits, tick marks, and labels.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Plotting n points with
plot(x, y)which processes each data point. - How many times: The plot function internally handles each of the n points once.
- Axis settings: Setting axis limits and ticks runs a fixed number of times, not depending on n.
The time to draw the plot grows as the number of points n increases, because each point is processed.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations for plotting points + fixed axis settings |
| 100 | About 100 operations for plotting points + fixed axis settings |
| 1000 | About 1000 operations for plotting points + fixed axis settings |
Pattern observation: The plotting time grows roughly in direct proportion to n, while axis formatting time stays about the same.
Time Complexity: O(n)
This means the time to create and format the plot grows linearly with the number of points plotted.
[X] Wrong: "Changing axis limits or ticks takes longer as the number of data points grows."
[OK] Correct: Axis formatting commands run a fixed number of times regardless of data size; only plotting points depends on n.
Understanding how plotting and axis formatting scale helps you write efficient visualization code and explain performance in real projects.
"What if we added a loop to update axis ticks inside the plotting loop? How would the time complexity change?"