0
0
MATLABdata~5 mins

First MATLAB program - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: First MATLAB program
O(n)
Understanding Time Complexity

When we write our first MATLAB program, it is helpful to see how the time it takes to run changes as we give it more work.

We want to know how the program's running time grows when the input size gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    n = 10;
    total = 0;
    for i = 1:n
        total = total + i;
    end
    disp(total);
    

This code adds up all numbers from 1 to n and shows the total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that adds each number to total.
  • How many times: It runs exactly n times, once for each number from 1 to n.
How Execution Grows With Input

As n gets bigger, the number of additions grows the same way.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the size of the input.

Common Mistake

[X] Wrong: "The loop runs faster because it just adds numbers."

[OK] Correct: Even simple additions take time, and since the loop runs n times, the total time grows with n.

Interview Connect

Understanding how loops affect running time is a key skill. It helps you explain your code clearly and shows you can think about efficiency.

Self-Check

"What if we changed the loop to run from 1 to n squared? How would the time complexity change?"