Input and output arguments in MATLAB - Time & Space Complexity
We want to understand how the time a MATLAB function takes changes when we change its inputs or outputs.
How does the size or number of input and output arguments affect the work done?
Analyze the time complexity of the following MATLAB function using input and output arguments.
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 vector x as input and returns a vector y where each element is the square of the corresponding element in x.
Look for loops or repeated steps that depend on input size.
- Primary operation: The
forloop that squares each element. - How many times: It runs once for each element in the input vector
x, sontimes.
As the input vector gets longer, the function does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 squaring steps |
| 100 | 100 squaring steps |
| 1000 | 1000 squaring steps |
Pattern observation: The work grows directly with the number of input elements. Double the input size, double the work.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the input size.
[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 element, so more elements mean more work.
Understanding how input size affects function time helps you explain your code clearly and shows you can think about efficiency in real projects.
"What if the function returned two output vectors instead of one? How would the time complexity change?"