Programming Previous page   Next Page

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:

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


Previous page  Creating a Logical Array Identifying Logical Arrays Next page

© 1994-2005 The MathWorks, Inc.