Why MATLAB is used in engineering and science - Performance Analysis
We want to understand how the time it takes to run MATLAB programs grows as the problem size gets bigger.
This helps us see why MATLAB is a good choice for engineering and science tasks.
Analyze the time complexity of the following MATLAB code snippet.
% Calculate the sum of squares from 1 to n
n = 1000;
sumSquares = 0;
for i = 1:n
sumSquares = sumSquares + i^2;
end
This code adds up the squares of numbers from 1 to n using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from 1 to n.
- How many times: It runs exactly n times, once for each number.
As n gets bigger, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions and multiplications |
| 100 | 100 additions and multiplications |
| 1000 | 1000 additions and multiplications |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the input.
[X] Wrong: "The loop runs faster because MATLAB is built for math."
[OK] Correct: Even though MATLAB is designed for math, the loop still runs once per number, so time grows with n.
Knowing how time grows helps you explain why MATLAB is good for many engineering tasks that need clear, predictable performance.
"What if we replaced the for-loop with a built-in vectorized operation? How would the time complexity change?"