Multiple plots (hold on) in MATLAB - Time & Space Complexity
When we use multiple plots with hold on in MATLAB, we add several drawing steps. We want to understand how the time to draw grows as we add more plots.
How does the time needed change when we plot more lines on the same figure?
Analyze the time complexity of the following code snippet.
x = linspace(0, 2*pi, 1000);
hold on;
for k = 1:n
y = sin(k*x);
plot(x, y);
end
hold off;
This code plots n sine waves on the same figure, each with 1000 points.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop runsntimes, each time callingplotto draw a line. - How many times: The loop repeats exactly
ntimes, once per sine wave.
Each additional plot adds a similar amount of work because it draws another line with 1000 points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 plot calls, each drawing 1000 points |
| 100 | 100 plot calls, each drawing 1000 points |
| 1000 | 1000 plot calls, each drawing 1000 points |
Pattern observation: The total work grows directly with the number of plots n. Doubling n roughly doubles the drawing time.
Time Complexity: O(n)
This means the time to draw grows in a straight line with the number of plots you add.
[X] Wrong: "Adding more plots won't affect the time much because the points are fixed at 1000."
[OK] Correct: Each plot call still draws all 1000 points, so more plots mean more total points drawn, increasing time linearly.
Understanding how repeated drawing commands affect performance helps you write efficient visualization code and shows you can think about how work grows with input size.
What if we increased the number of points per plot from 1000 to 10,000? How would the time complexity change?