Function definition syntax in MATLAB - Time & Space 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?
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 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.
As the input list gets bigger, the function does more work by squaring each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the input size. Double the input, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the input list.
[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.
Understanding how loops affect time helps you explain your code clearly and shows you know how programs grow with input size.
"What if we changed the function to square only the first half of the input list? How would the time complexity change?"