How does logical indexing work?

1,077 views (last 30 days)
Doug Hull
Doug Hull on 18 Jan 2011
Can I get a short primer on this?

Accepted Answer

Doug Hull
Doug Hull on 18 Jan 2011
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]

More Answers (1)

Anish
Anish on 18 Jan 2011
Assume A is a MxN matrix.
Let "tf" be a MxN logical matrix.
Then A(tf) extracts all elements of A corresponding to all true elements in tf
A = rand(5); % Random 5x5 matrix
tf = A > .5 % Logical matrix of same size 5x5
A(tf) % All values in A greater than .5 as a column
For more help, see Steve's excellent blog in this:
Or good old MATLAB doc:

Communities

More Answers in the  Power Electronics Control

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!