From the Getting Started book:
The logical vectors created from logical and relational operations can be used to reference subarrays. Suppose X is an ordinary matrix and L is a matrix of the same size that is the result of some logical operation. Then X(L) specifies the elements of X where the elements of L are nonzero.
Here's a short example of logical indexing to specify certain array elements:
m = magic(5)
% Get the logical matrix which is zero where
% m <= 20 and 1 where m >= 21
bigNumbersLocations = m > 20
% Extract those big numbers into an array
% Method #1:
bigNumbers = zeros(size(m));
bigNumbers(bigNumbersLocations) = m(bigNumbersLocations)
% Method #2:
bigNumbers2 = m;
bigNumbers2(~bigNumbersLocations) = 0
% Display the big numbers. It will be a 1D vector.
m(bigNumbersLocations)
m =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
bigNumbersLocations =
0 1 0 0 0
1 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
bigNumbers =
0 24 0 0 0
23 0 0 0 0
0 0 0 0 22
0 0 0 21 0
0 0 25 0 0
bigNumbers2 =
0 24 0 0 0
23 0 0 0 0
0 0 0 0 22
0 0 0 21 0
0 0 25 0 0
ans =
23
24
25
21
22
[From the MATLAB FAQ of Ancient Times]