Local functions in MATLAB - Time & Space Complexity
When using local functions in MATLAB, it's important to see how their execution time grows as input size changes.
We want to know how calling a local function inside a main function affects overall running time.
Analyze the time complexity of the following code snippet.
function result = mainFunction(n)
total = 0;
for i = 1:n
total = total + localAdd(i);
end
result = total;
function y = localAdd(x)
y = x + 1;
end
end
This code sums numbers from 1 to n, adding 1 to each number using a local function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 1 to n, calling the local function each time.
- How many times: The local function is called exactly n times, once per loop iteration.
As n grows, the number of times the local function runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to localAdd |
| 100 | About 100 calls to localAdd |
| 1000 | About 1000 calls to localAdd |
Pattern observation: The work grows directly with n; doubling n doubles the calls.
Time Complexity: O(n)
This means the total time grows in a straight line as the input size increases.
[X] Wrong: "Local functions run only once, so they don't affect time much."
[OK] Correct: Even though the function is local, it runs every time it is called inside the loop, so its cost adds up with n.
Understanding how local functions impact time helps you explain code efficiency clearly and shows you can analyze function calls inside loops.
"What if the local function itself contained a loop running n times? How would the time complexity change?"