0
0
MATLABdata~5 mins

Multiple outputs in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Multiple outputs
O(n)
Understanding Time Complexity

We want to see how the time needed changes when a MATLAB function gives back more than one answer.

How does asking for multiple results affect the work the program does?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

function [sumVal, prodVal] = sumAndProduct(arr)
    n = length(arr);
    sumVal = 0;
    prodVal = 1;
    for i = 1:n
        sumVal = sumVal + arr(i);
        prodVal = prodVal * arr(i);
    end
end

This function calculates the sum and product of all elements in an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single loop that goes through each element of the array once.
  • How many times: Exactly as many times as there are elements in the array (n times).
How Execution Grows With Input

As the array gets bigger, the loop runs more times, doing a fixed amount of work each time.

Input Size (n)Approx. Operations
10About 10 additions and 10 multiplications
100About 100 additions and 100 multiplications
1000About 1000 additions and 1000 multiplications

Pattern observation: The work grows directly with the number of elements. Double the elements, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to get both outputs grows in a straight line with the size of the input array.

Common Mistake

[X] Wrong: "Getting two outputs means the program does twice as much work, so the time complexity doubles to O(2n)."

[OK] Correct: The loop still runs once per element doing both tasks together, so the time grows linearly, not doubled in complexity terms.

Interview Connect

Understanding how multiple outputs affect time helps you explain your code clearly and shows you know how work scales in real programs.

Self-Check

"What if the function used two separate loops instead of one to calculate sum and product? How would the time complexity change?"