Logical Arrays & find
A logical array is an array of true/false values, usually the result of a comparison. Using one as an index (logical indexing) selects exactly the elements where it is true. This is one of MATLAB's most powerful features: filtering data takes a single line and no loop.
Logical indexing
rain = [0 3.2 0 12.5 0.4 0 7.1]; % mm per day
wet = rain > 0
disp(rain(wet)) % only the rainy days
fprintf('%d rainy days, %.1f mm in total\n', sum(wet), sum(rain(wet)));wet =
0 1 0 1 1 0 1
3.2000 12.5000 0.4000 7.1000
4 rainy days, 23.2 mm in total
The logical array must be the same size as the array being indexed (or shorter). sum of a logical array counts the trues.
Changing values with a mask
A logical index on the left of = changes only the selected elements. This is the idiomatic way to clean data:
readings = [21.5 -999 22.1 23.0 -999 21.8]; % -999 means "sensor error"
readings(readings == -999) = NaN;
disp(readings)
fprintf('Mean of valid readings: %.2f\n', mean(readings(~isnan(readings))));
scores = [45 78 102 88 -3];
scores(scores > 100) = 100; % clip to the valid range
scores(scores < 0) = 0;
disp(scores) 21.5000 NaN 22.1000 23.0000 NaN 21.8000
Mean of valid readings: 22.10
45 78 100 88 0
Combining conditions
Use the element-wise operators & (and), | (or) and ~ (not) to combine masks. Remember the parentheses around each comparison when it makes the intent clearer:
ages = [12 25 37 16 68 45 71];
adults = ages(ages >= 18 & ages < 65)
youngOrOld = ages(ages < 18 | ages >= 65)
notTeen = ages(~(ages >= 13 & ages <= 19))adults =
25 37 45
youngOrOld =
12 16 68 71
notTeen =
12 25 37 68 45 71
find: positions instead of a mask
find(mask) returns the indices where a logical array is true. Use it when you need the positions themselves, the first few matches, or row/column coordinates:
v = [5 0 8 0 0 3];
disp(find(v)) % positions of nonzero elements
disp(find(v == 0))
disp(find(v > 4, 1)) % only the first match
noMatch = find(v > 100); % no match: an empty array
disp(isempty(noMatch)) 1 3 6
2 4 5
1
1
When nothing matches, find returns an empty array, so test the result with isempty before using it.
On a matrix, find with two outputs gives row and column indices:
M = [0 7 0; 4 0 9];
[r, c] = find(M);
fprintf('M(%d,%d) = %d\n', [r c M(M ~= 0)]');M(2,1) = 4
M(1,2) = 7
M(2,3) = 9
Matches come back in column order, the same order as linear indexing.
any, all and nnz
| Function | Question it answers |
|---|---|
any(mask) |
Is at least one element true? |
all(mask) |
Are all elements true? |
nnz(mask) |
How many elements are nonzero/true? |
sum(mask) |
Same as nnz for a vector |
marks = [55 72 38 90 64];
fprintf('Anyone failed (< 40)? %d\n', any(marks < 40));
fprintf('Everyone passed? %d\n', all(marks >= 40));
fprintf('Distinctions (>= 70): %d\n', nnz(marks >= 70));
fprintf('Pass rate: %.0f%%\n', 100 * mean(marks >= 40));Anyone failed (< 40)? 1
Everyone passed? 0
Distinctions (>= 70): 2
Pass rate: 80%
mean of a logical array is the fraction of trues, a handy shortcut for percentages.
Test yourself
For v = [3 8 1 9], what is v(v > 2)?
[1 1 0 1][3 8 9][1 2 4]- 3
What does find([0 4 0 6]) return?
[4 6][2 4][0 1 0 1]- 2
Which line sets every negative element of x to zero?
x(x < 0) = 0;x = x < 0;if x < 0, x = 0; endx(find(x)) = 0;