Logical indexing in MATLAB - Time & Space Complexity
Logical indexing lets us pick elements from an array using true or false values. We want to know how the time to do this changes as the array gets bigger.
How does the work grow when we select elements this way?
Analyze the time complexity of the following code snippet.
A = rand(1, n); % Create an array of n random numbers
idx = A > 0.5; % Logical array where elements > 0.5 are true
B = A(idx); % Select elements where idx is true
This code creates an array, finds which elements are bigger than 0.5, and then selects those elements.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element of A to see if it is greater than 0.5.
- How many times: Once for each element in the array, so n times.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows directly with the size of the array. Double the size, double the work.
Time Complexity: O(n)
This means the time to select elements grows in a straight line with the number of elements.
[X] Wrong: "Logical indexing is instant no matter how big the array is."
[OK] Correct: Even though logical indexing looks simple, MATLAB must check each element once, so bigger arrays take more time.
Understanding how logical indexing scales helps you write efficient code and explain your choices clearly in interviews. It shows you know how data size affects performance.
"What if we used a loop to select elements instead of logical indexing? How would the time complexity change?"