Multiple outputs in MATLAB - Time & Space 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?
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 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).
As the array gets bigger, the loop runs more times, doing a fixed amount of work each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions and 10 multiplications |
| 100 | About 100 additions and 100 multiplications |
| 1000 | About 1000 additions and 1000 multiplications |
Pattern observation: The work grows directly with the number of elements. Double the elements, double the work.
Time Complexity: O(n)
This means the time to get both outputs grows in a straight line with the size of the input array.
[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.
Understanding how multiple outputs affect time helps you explain your code clearly and shows you know how work scales in real programs.
"What if the function used two separate loops instead of one to calculate sum and product? How would the time complexity change?"