How does logical indexing work?

조회 수: 100 (최근 30일)
Doug Hull
Doug Hull 2011년 1월 18일
Can I get a short primer on this?

채택된 답변

Doug Hull
Doug Hull 2011년 1월 18일
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]

추가 답변 (1개)

Anish
Anish 2011년 1월 18일
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:

커뮤니티

더 많은 답변 보기:  Power Electronics Community

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by