Function handles in MATLAB - Time & Space Complexity
We want to understand how using function handles affects the time it takes for a MATLAB program to run.
Specifically, we ask: how does calling a function through a handle change the number of steps as input grows?
Analyze the time complexity of the following code snippet.
f = @(x) x^2; % function handle that squares input
n = 1000;
result = zeros(1,n);
for i = 1:n
result(i) = f(i); % call function handle
end
This code creates a function handle to square a number, then calls it n times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the function handle inside the loop.
- How many times: Exactly n times, once per loop iteration.
Each time n doubles, the number of function calls doubles too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to the function handle |
| 100 | 100 calls to the function handle |
| 1000 | 1000 calls to the function handle |
Pattern observation: The total work grows directly with n, because each input requires one function call.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size increases.
[X] Wrong: "Using a function handle makes the code run much slower, so the time grows faster than the input size."
[OK] Correct: Calling a function handle adds a tiny fixed cost per call, but the total time still grows linearly with the number of calls.
Understanding how function handles affect time helps you explain your code choices clearly and shows you know how MATLAB runs your programs efficiently.
"What if the function handle called another function inside it? How would that affect the time complexity?"