Programming |
How Logical Arrays Are Used
MATLAB has two primary uses for logical arrays:
Most mathematics operations are not supported on logical values.
Using Logicals in Conditional Statements
Conditional statements are useful when you want to execute a block of code only when a certain condition is met. For example, the sprintf
command shown below is valid only if str
is a nonempty string. The statement
checks for this condition and allows the sprintf
to execute only if it is true
:
str = 'Hello'; if ~isempty(str) && ischar(str) sprintf('Input string is ''%s''', str) end ans = Input string is 'Hello'
Using Logicals in Array Indexing
MATLAB supports a type of array indexing that uses one array as the index into another array. For example, array B
below indexes into elements 1
, 3
, 6
, 7
, and 10
of array A
:
In this case, the numeric values of array B
designate the intended elements of A
.
Another type of array index, a logical index, designates the elements of A
based on their position in the indexing array, B
. In this masking type of operation, every true
element in the indexing array is treated as a positional index into the array being accessed.
Logical Indexing Example 1. This next example creates logical array B
that satisfies the condition A > 0.5
, and uses the positions of ones in B
to index into A
. This is called logical indexing:
A = rand(5); B = A > 0.5; A(B) = 0 A = 0.2920 0.3567 0.1133 0 0.0595 0 0.4983 0 0.2009 0.0890 0.3358 0.4344 0 0.2731 0.2713 0 0 0 0 0.4091 0.0534 0 0 0 0.4740
A simpler way to express this is
Logical Indexing Example 2. The next example highlights the location of the prime numbers in a magic square using logical indexing to set the nonprimes to 0
:
A = magic(4) A = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 B = isprime(A) B = 0 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 A(~B) = 0; % Logical indexing A A = 0 2 3 13 5 11 0 0 0 7 0 0 0 0 0 0
Creating a Logical Array | Identifying Logical Arrays |
© 1994-2005 The MathWorks, Inc.