Logical values in MATLAB - Time & Space Complexity
Let's see how using logical values affects the time it takes for a program to run.
We want to know how the program's steps grow when working with true or false values.
Analyze the time complexity of the following code snippet.
n = 1000;
A = rand(n,1);
B = A > 0.5 & A;
countTrue = sum(B);
This code creates a list of numbers, checks which are greater than 0.5, combines logical checks, and counts how many are true.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Logical AND operation on each element of the array.
- How many times: Once for each of the n elements in the array.
Each element is checked once, so the work grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 logical checks |
| 100 | About 100 logical checks |
| 1000 | About 1000 logical checks |
Pattern observation: When the input size doubles, the number of operations also doubles.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of elements you check.
[X] Wrong: "Logical operations are instant and don't add to time."
[OK] Correct: Even simple true/false checks happen for each item, so more items mean more time.
Understanding how logical checks scale helps you explain how your code handles bigger data clearly and confidently.
"What if we replaced the logical AND with a nested loop checking pairs of elements? How would the time complexity change?"