Comparison operators in MATLAB - Time & Space Complexity
We want to understand how long it takes to compare values in MATLAB as the input size grows.
How does the time needed change when we compare many elements?
Analyze the time complexity of the following code snippet.
arr = randi(100, 1, n);
count = 0;
for i = 1:n
if arr(i) > 50
count = count + 1;
end
end
This code counts how many numbers in the array are greater than 50.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing each element to 50 using the > operator inside a loop.
- How many times: Exactly once for each element in the array, so n times.
As the array gets bigger, the number of comparisons grows directly with the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: Doubling the input doubles the number of comparisons.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of elements.
[X] Wrong: "Comparison operators take constant time no matter how many elements we have."
[OK] Correct: While one comparison is quick, doing many comparisons one after another adds up, so total time grows with the number of elements.
Understanding how simple comparisons add up helps you explain how your code handles bigger data smoothly and efficiently.
"What if we compared pairs of elements inside two nested loops? How would the time complexity change?"