0
0
MATLABdata~5 mins

Multiple plots (hold on) in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Multiple plots (hold on)
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop runs n times, each time calling plot to draw a line.
  • How many times: The loop repeats exactly n times, once per sine wave.
How Execution Grows With Input

Each additional plot adds a similar amount of work because it draws another line with 1000 points.

Input Size (n)Approx. Operations
1010 plot calls, each drawing 1000 points
100100 plot calls, each drawing 1000 points
10001000 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.

Final Time Complexity

Time Complexity: O(n)

This means the time to draw grows in a straight line with the number of plots you add.

Common Mistake

[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.

Interview Connect

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.

Self-Check

What if we increased the number of points per plot from 1000 to 10,000? How would the time complexity change?