3.8: Logical Arrays and Logical Indexing

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    3.8: Logical Arrays and Logical Indexing

    So far, we have accessed elements in an array by using their index numbers. For example, if we have the following array:

    myArray = [10 25 30 45 50];

    we can access the second element by typing:

    myArray(2)

    MATLAB returns:

    ans = 
          25
    

    This is called numeric indexing because we are using a number, such as 2, to tell MATLAB which element we want.

    Logical indexing is different. Instead of telling MATLAB the index numbers directly, we give MATLAB an array of true and false values. MATLAB then keeps the elements that correspond to true and ignores the elements that correspond to false.

    A logical array is an array whose elements are logical values. In MATLAB, logical values are displayed as true and false, or sometimes as 1 and 0, where 1 means true and 0 means false.

    Selecting Values with a Logical Array

    Suppose we have this numerical array:

    myArray = [10 25 30 45 50];

    Now suppose we create this logical array:

    logicArray = [false true false true true];

    This logical array has five elements. The second, fourth, and fifth elements are true. If we use logicArray as an index:

    selectedValues = myArray(logicArray)

    MATLAB returns:

    selectedValues =
    
        25    45    50

    Why? MATLAB looks at the logical array position by position:

    Position

    myArray value

    logicArray value

    Selected?

    1

    10

    false

    No

    2

    25

    true

    Yes

    3

    30

    false

    No

    4

    45

    true

    Yes

    5

    50

    true

    Yes

    So logical indexing is a way of saying: return the elements where the condition is true.

    This is one of the most useful ideas in MATLAB. Instead of saying “give me elements 2, 4, and 5,” we can say something more meaningful, such as “give me all values greater than 80” or “give me all positive values.”

    Creating Logical Arrays Using Relational Operators

    Usually, we do not type logical arrays manually. Instead, we create them using relational operators. A relational operator compares values and returns logical values.

    Operator

    Meaning

    >

    greater than

    <

    less than

    >=

    greater than or equal to

    <=

    less than or equal to

    ==

    equal to

    ~=

    not equal to

    For example, suppose we have quiz scores:

    scores = [72 91 85 63 100 58 77];

    If we want to find which scores are at least 80, we can write:

    passingIndex = scores >= 80

    MATLAB returns a logical array. The values 91, 85, and 100 satisfy the condition, so those positions are true. The other positions are false.

    passingIndex =
    
      1x7 logical array
    
       0   1   1   0   1   0   0

    Now we can use this logical array to extract only the scores that meet the condition:

    passingScores = scores(passingIndex)

    MATLAB returns:

    passingScores =
    
        91    85   100

    We can also combine these two steps into one line:

    passingScores = scores(scores >= 80)

    Read this line in plain English as: passingScores equals the elements of scores where scores is greater than or equal to 80.

    Example \(\PageIndex{1}\)

    Finding the positive numbers in an array.

    nums = [-4 7 0 -2 9 15 -1];
    
    % To find only the positive values, we create a logical array.
    
    positiveIndex = nums > 0
    
    % use the logical array to extract the positive values.
    
    positiveNums = nums(positiveIndex)
    Solution
    positiveIndex =
    
    1×7 logical array
    
    0 1 0 0 1 1 0
    
    
    positiveNums =
    
    7 9 15

    Add example text here.

    In the example above, the last two lines can be combined into one line:

    positiveNums = nums(nums > 0)

    Replacing Values Using Logical Indexing

    Logical indexing is not only useful for extracting values. It can also be used to change values.

    Suppose a sensor recorded the following temperatures:

    temps = [72 75 999 74 73 999 71];

    Here, the value 999 was used to represent an invalid sensor reading. We can replace those invalid readings with NaN, which stands for “Not a Number”:

    temps(temps == 999) = NaN

    The result is:

    temps =
    
        72    75   NaN    74    73   NaN    71

    This line means: find the elements of temps that are equal to 999, and replace those elements with NaN. This is a powerful pattern for cleaning experimental data.

    Counting Values That Meet a Condition

    Logical arrays are also useful because MATLAB treats true as 1 and false as 0 in many calculations. This means we can count how many values satisfy a condition by using sum.

    scores = [72 91 85 63 100 58 77];
    passingIndex = scores >= 80;
    numPassing = sum(passingIndex)

    Since the logical array has three true values, MATLAB returns:

    numPassing =
    
         3

    So three students scored at least 80. We can also write this directly:

    numPassing = sum(scores >= 80)

    Read this as: count how many elements in scores are greater than or equal to 80.

    Combining Relational and Logical Operators

    Sometimes one condition is not enough. For example, suppose we want to find all values that are greater than 0 and less than 100.

    nums = [-5 -99 82 -105 102 33];

    We can combine two conditions using the & operator, which means and:

    validIndex = (nums > 0) & (nums < 100)

    The parentheses make the code easier to read. The result is true only where both conditions are true.

    validNums = nums(validIndex)

    The result is:

    validNums =
    
        82    33

    The | operator means or. At least one condition must be true. For example, to find values that are either less than 0 or greater than 100:

    outOfRangeNums = nums((nums < 0) | (nums > 100))

    The result is:

    outOfRangeNums =
    
        -5   -99  -105   102

    The ~ operator means not. It reverses true and false values. For example, to extract only the nonzero values from an array:

    data = [4 0 7 0 9 2 0];
    nonzeroValues = data(data ~= 0)

    The result is:

    nonzeroValues =
    
         4     7     9     2

    Example: Cubing Only the Positive Values

    Suppose we are given this array:

    x = [3 2 -1 5 0];

    We want to create a new array y that contains the positive elements of x cubed, but replaces zero and negative values with zero. One compact way to do this is:

    y = (x.^3) .* (x > 0)

    Let us break this down. First, x.^3 cubes every element:

    [27 8 -1 125 0]

    Next, x > 0 creates this logical array:

    [1 1 0 1 0]

    Then MATLAB multiplies element by element:

    [27 8 -1 125 0] .* [1 1 0 1 0]

    which gives:

    [27 8 0 125 0]

    This works because true behaves like 1 and false behaves like 0 in this numerical operation.

    Example \(\PageIndex{2}\)

    Extracting First, Then Calculating.

    Now suppose we want a new array that contains only the cubed positive values from x, but only if the original values are less than 4.

    x = [3 2 -1 5 0];
    xIndex = (x > 0) & (x < 4);
    z = x(xIndex).^3
    Solution
    z =
    
        27     8

    The values selected from x are 3 and 2, because they are both positive and less than 4. Then MATLAB cubes them.

    This is different from the previous example. In the previous example, the output y had the same size as x. In this example, the output z contains only the selected values.

    Caution

    A logical indexing array must have the same number of elements as the array it is indexing.

    Common Mistakes with Logical Indexing

    A common mistake is using = instead of ==. The single equal sign is used for assignment. The double equal sign is used for comparison.

    The following code does not check whether scores is equal to 85. It replaces the variable scores with the value 85:

    scores = 85

    To compare values, use ==:

    scores == 85

    Another common mistake is using && instead of & with arrays. For element-by-element comparisons of arrays, use &:

    (nums > 0) & (nums < 100)

    Do not use && for this array operation:

    (nums > 0) && (nums < 100)

    The operator && is mainly used for scalar logical expressions, such as inside certain if statements. Similarly, use | for element-by-element OR with arrays, not ||.


    This page titled 3.8: Logical Arrays and Logical Indexing was last modified on Tue, 30 Jun 2026 02:11:55 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.