How does logical indexing work?

438 次查看(过去 30 天)
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 Control

类别

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