Why functions organize MATLAB code - Performance Analysis
When we use functions in MATLAB, we want to see how the time to run the code changes as the input grows.
We ask: How does calling a function affect the total work done?
Analyze the time complexity of the following code snippet.
function result = sumArray(arr)
total = 0;
for i = 1:length(arr)
total = total + arr(i);
end
result = total;
end
% Main script
values = 1:1000;
sumResult = sumArray(values);
This code defines a function that adds all numbers in an array, then calls it with 1000 numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the function that adds each element.
- How many times: It runs once for each element in the input array.
As the array gets bigger, the function does more additions, one per element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Using a function adds extra time that grows with input size."
[OK] Correct: The function itself just runs the loop once; calling it does not multiply the work. The main cost is the loop inside, not the function call overhead.
Understanding how functions affect time helps you write clear code without worrying about hidden slowdowns. This skill shows you can balance good design with performance.
"What if the function called itself recursively to sum the array? How would the time complexity change?"