0
0
MATLABdata~5 mins

Function definition syntax in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function definition syntax
O(n)
Understanding Time Complexity

We want to see how the time it takes to run a function changes as the input size grows.

How does the function's work increase when we give it bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

function y = squareElements(x)
    n = length(x);
    y = zeros(1, n);
    for i = 1:n
        y(i) = x(i)^2;
    end
end

This function takes a list of numbers and returns a new list where each number is squared.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through each element of the input list.
  • How many times: It runs once for every element in the input list, so n times.
How Execution Grows With Input

As the input list gets bigger, the function does more work by squaring each number.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The work grows directly with the input size. Double the input, double the work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The function runs in constant time because it just squares numbers."

[OK] Correct: Even though squaring one number is quick, the function does it for every number in the list, so the total time depends on how many numbers there are.

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you know how programs grow with input size.

Self-Check

"What if we changed the function to square only the first half of the input list? How would the time complexity change?"