Lesson 7 of 45 ยท Matrices and Arrays
Logical Indexing and find
Select, count and change MATLAB or Octave array elements with comparison masks, find, any, all and nnz, with runnable Python stand-ins.
Real data is rarely handled element by element. You usually want sentences like "all readings above 30", "the first day it rained" or "replace every missing value with zero". In MATLAB and Octave you say these things with logical indexing: you compare an array with a value, get back an array of true and false flags, and use those flags to pick, count or change elements.
This lesson builds on Indexing and Slicing. Here the index is no longer a list of positions but a mask of the same size as the array. The function find converts a mask back into positions when you need them.
MATLAB and Octave are not installed on this site. The matlab blocks below are read-only. Each TryIt is a Python (NumPy) stand-in that does the same work, with helper code that copies MATLAB's 1-based, column-major behavior. Where the stand-in differs from the real thing, the text says so.
Mask first, then use it
The same mask can select, count and overwrite.
find turns a mask into positions
Comparison operators make masks
The comparison operators are <, <=, >, >=, == and ~= (not equal; Octave also accepts !=). They work on every element at once and return a logical array the same size as the input.
A = magic(3) % 8 1 6 % 3 5 7 % 4 9 2 A > 5 % 1 0 1 % 0 0 1 % 0 1 0
A logical array holds 1 for true and 0 for false, but its class is logical, not double. That difference matters: A(mask) with a logical mask means "pick where true", while A([1 0 1]) with numbers would mean "pick element 1, then element 0", and 0 is not a valid index.
To combine conditions, use the element-wise operators & (and), | (or) and ~ (not). xor(a, b) is true when exactly one is true.
inRange = (A > 2) & (A < 8); % 3 <= A <= 7 style test odd = mod(A, 2) == 1; either = (A > 5) | odd;
Do not chain comparisons like 2 < A < 8. MATLAB reads it as (2 < A) < 8, which compares a 0/1 result with 8 and is always true. Write (A > 2) & (A < 8). Also avoid && and || for arrays: they are short-circuit operators for single true/false values.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
NumPy prints True and False where MATLAB prints 1 and 0. The important detail is the line M.T[mask.T]: MATLAB lists selected elements down the columns first (column-major order), so the stand-in transposes before it indexes. In plain NumPy, M[mask] would go row by row and return [8 6 7 9] instead of MATLAB's [8 9 6 7].
Selecting and counting with a mask
Put the mask inside the parentheses to get the true elements as a column vector, whatever shape the input had:
A(A > 5) % 8 % 9 % 6 % 7
Because a true flag counts as 1, summing a mask counts matches. nnz ("number of nonzeros") does the same job and reads more clearly:
sum(A(:) > 5) % 4 nnz(A > 5) % 4 mean(A(:) > 5) % fraction of elements above 5
The mean of a mask is a handy shortcut for "what share of values satisfy this?". Note the A(:): it turns the matrix into one column so sum does not return one total per column.
find: from flags to positions
find returns the positions of the nonzero (true) elements. With one output it gives linear indices, which count down the columns:
idx = find(A > 5)' % 1 6 7 8 [r, c] = find(A > 5); % with two outputs: row and column numbers % r' = 1 3 1 2 c' = 1 2 3 3
find(mask, n) returns only the first n hits and find(mask, n, 'last') the last n. That makes "when did it first happen?" a one-liner, and it returns an empty array (not an error) when nothing matches. Always check isempty(idx) before using idx(1).
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
The last two examples show assignment through a mask. w(mod(w, 2) == 0) = 0 overwrites only the even elements, and the matrix keeps its shape. The right-hand side may be a single value (it is applied to every selected element) or a vector with exactly as many elements as there are true flags.
w = 1:6; w(mod(w, 2) == 0) = 0 % 1 0 3 0 5 0 A(A > 5) = 0 % zero out the large entries A(A > 5) = [10 20 30 40]; % fine only if exactly 4 elements match
any, all and missing data
any asks "is at least one element true?" and all asks "are they all true?". On a vector they return one answer. On a matrix they work down each column and return a row of answers, so use any(any(X)), any(X(:)) or any(X, 'all') (newer MATLAB) for a single verdict. Give a dimension to work along rows instead: all(X, 2).
The most important use of masks is cleaning data. The special value NaN ("not a number") marks a missing measurement, and it is never equal to anything, not even itself. Test for it with isnan, never with == NaN:
x = [3 NaN 7 NaN 1]; x == x % 1 0 1 0 1 (NaN is the only value not equal to itself) isnan(x) % 0 1 0 1 0 mean(x(~isnan(x))) % mean of the valid values x(isnan(x)) = 0; % replace the gaps
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
NumPy's axis=0 corresponds to MATLAB's dimension 1 (down the columns) and axis=1 to dimension 2. The last line, np.where(T > 28, 28, T), caps the values. In MATLAB you would write min(T, 28) or T(T > 28) = 28.
Useful patterns
- Count by condition:
nnz(scores >= 50). - Percentage:
100 * mean(scores >= 50). - Filter two arrays together:
keep = ages >= 18; names(keep)andscores(keep)stay aligned because the same mask is used. - Remove elements:
x(x < 0) = [];deletes the matching elements (the array shrinks). - Convert a mask to numbers:
double(mask); to a mask from numbers:logical(v)(nonzero becomes true). - Floating-point equality:
0.1 + 0.2 == 0.3is false. Compare with a tolerance:abs(a - b) < 1e-9.
Check your understanding
Quick check ยท 4 questions
of 4 answered You scored / 4 ยท perfect!
-
1. For
A = magic(3), what doesA(A > 5)return?A > 5is the mask; indexing with it returns the true elements as a column vector in column-major order, so 8, 9, 6, 7. -
2. Which expression correctly tests whether
xis between 2 and 8?&combines two masks element by element. A chained comparison is evaluated left to right and gives the wrong answer, and&&is meant for scalar conditions. -
3. What does
find(v > 13, 1)return when no element ofvexceeds 13?findreturns an empty array when nothing matches, so test withisemptybefore using the result as an index. -
4. How should you detect missing values stored as
NaN?NaNis not equal to anything, including itself, sox == NaNis always false.isnanis the right test.
Summary
- Comparisons (
<,>,==,~=, ...) return logical arrays; combine them with&,|,~andxor. A(mask)selects the true elements as a column vector in column-major order, andA(mask) = valuechanges them in place.nnz(mask),sum(mask)andmean(mask)count matches and give proportions.findreturns linear indices (or row and column numbers with two outputs), supports a count and'last', and returns an empty array when nothing matches.anyandallwork down columns by default; use a dimension argument or(:)for a single answer.- Test for missing data with
isnan, and compare floats with a tolerance.
Next: combine and rearrange arrays in Reshaping, Joining and Sorting.
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of MATLAB / Octave lessons completed