0
0
MATLABdata~5 mins

Logical indexing in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Logical indexing
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The number of operations grows directly with the size of the array. Double the size, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to select elements grows in a straight line with the number of elements.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we used a loop to select elements instead of logical indexing? How would the time complexity change?"