Anonymous functions in MATLAB - Time & Space Complexity
We want to see how the time it takes to run anonymous functions changes as we use them more.
How does the number of times we call an anonymous function affect the total work done?
Analyze the time complexity of the following code snippet.
f = @(x) x^2; % anonymous function to square a number
n = 1000;
result = zeros(1,n);
for i = 1:n
result(i) = f(i);
end
This code creates an anonymous function to square a number, then calls it n times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the anonymous function inside the for-loop.
- How many times: The loop runs n times, so the function is called n times.
Each time we increase n, the number of function calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to the anonymous function |
| 100 | 100 calls to the anonymous function |
| 1000 | 1000 calls to the anonymous function |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the total time grows in a straight line as we increase the number of calls.
[X] Wrong: "Anonymous functions run slower and add extra hidden loops making time grow faster."
[OK] Correct: Calling an anonymous function is like calling any other function once per loop; it does not add extra loops or hidden repeated work.
Understanding how function calls inside loops affect time helps you explain code efficiency clearly and confidently.
"What if we replaced the anonymous function call inside the loop with direct calculation? How would the time complexity change?"