0
0
MATLABdata~5 mins

Local functions in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Local functions
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of times the local function runs grows the same way.

Input Size (n)Approx. Operations
10About 10 calls to localAdd
100About 100 calls to localAdd
1000About 1000 calls to localAdd

Pattern observation: The work grows directly with n; doubling n doubles the calls.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows in a straight line as the input size increases.

Common Mistake

[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.

Interview Connect

Understanding how local functions impact time helps you explain code efficiency clearly and shows you can analyze function calls inside loops.

Self-Check

"What if the local function itself contained a loop running n times? How would the time complexity change?"