A(A<9 & ~mod(A,2))
ans = 3×1
2
2
8
The result is a list of all even elements in A that are less than 9. The use of the logical NOT operator,
~, converts the matrix mod(A,2) into a logical matrix, with a value of logical 1 (true) located where
an element is evenly divisible by 2.
Finally, find the elements in A that are less than 9 and even numbered and not equal to 2.
A(A<9 & ~mod(A,2) & A~=2)
ans = 8
The result, 8, is even, less than 9, and not equal to 2. It is the only element in A that satisfies all three
conditions.
Use the find function to get the index of the element equal to 8 that satisfies the conditions.
find(A<9 & ~mod(A,2) & A~=2)
ans = 14
The result indicates that A(14) = 8.
Replace Values That Meet a Condition
Sometimes it is useful to simultaneously change the values of several existing array elements. Use
logical indexing with a simple assignment statement to replace the values in an array that meet a
condition.
Replace all values in A that are greater than 10 with the number 10.
A(A>10) = 10
A = 5×5
10
2
3
3
10
10
5
10
7
1
2
9
10
10
10
10
10
8
10
10
10
10
10
10
10
Next, replace all values in A that are not equal to 10 with a NaN value.
A(A~=10) = NaN
A = 5×5
10
NaN
NaN
NaN
10
10
NaN
10
NaN
NaN
NaN
NaN
10
10
10
10
10
NaN
10
10
5 The Logical Class
5-4
ans = 3×1
2
2
8
The result is a list of all even elements in A that are less than 9. The use of the logical NOT operator,
~, converts the matrix mod(A,2) into a logical matrix, with a value of logical 1 (true) located where
an element is evenly divisible by 2.
Finally, find the elements in A that are less than 9 and even numbered and not equal to 2.
A(A<9 & ~mod(A,2) & A~=2)
ans = 8
The result, 8, is even, less than 9, and not equal to 2. It is the only element in A that satisfies all three
conditions.
Use the find function to get the index of the element equal to 8 that satisfies the conditions.
find(A<9 & ~mod(A,2) & A~=2)
ans = 14
The result indicates that A(14) = 8.
Replace Values That Meet a Condition
Sometimes it is useful to simultaneously change the values of several existing array elements. Use
logical indexing with a simple assignment statement to replace the values in an array that meet a
condition.
Replace all values in A that are greater than 10 with the number 10.
A(A>10) = 10
A = 5×5
10
2
3
3
10
10
5
10
7
1
2
9
10
10
10
10
10
8
10
10
10
10
10
10
10
Next, replace all values in A that are not equal to 10 with a NaN value.
A(A~=10) = NaN
A = 5×5
10
NaN
NaN
NaN
10
10
NaN
10
NaN
NaN
NaN
NaN
10
10
10
10
10
NaN
10
10
5 The Logical Class
5-4
