How does logical indexing work?

935 Ansichten (letzte 30 Tage)
Doug Hull
Doug Hull am 18 Jan. 2011
Can I get a short primer on this?

Akzeptierte Antwort

Doug Hull
Doug Hull am 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]

Weitere Antworten (1)

Anish
Anish am 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:

Communitys

Weitere Antworten in  Power Electronics Control

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by