Logical Classes

Overview

The logical data type represents a logical true or false state using the numbers 1 and 0, respectively. Certain MATLAB® functions and operators return logical true or false to indicate whether a certain condition was found to be true or not. For example, the statement 50>40 returns a logical true value.

Logical data does not have to be scalar; MATLAB supports arrays of logical values as well. For example, the following statement returns a vector of logicals indicating false for the first two elements and true for the last three:

[30 40 50 60 70] > 40
ans =
     0     0     1     1     1

This statement returns a 4-by-4 array of logical values:

x = magic(4) >= 9
x =
     1     0     0     1
     0     1     1     0
     1     0     0     1
     0     1     1     0

The MATLAB functions that have names beginning with is (e.g., ischar, issparse) also return a logical value or array:

a = [2.5 6.7 9.2 inf 4.8];

isfinite(a)
ans =
     1     1     1     0     1

Logical arrays can also be sparse as long as they have no more than two dimensions:

x = sparse(magic(20) > 395)
x =
   (1,1)        1
   (1,4)        1
   (1,5)        1
  (20,18)       1
  (20,19)       1

Identifying Logical Arrays

This table shows the commands you can use to determine whether or not an array x is logical. The last function listed, cellfun, operates on cell arrays, which you can read about in the section Cell Arrays.

Command

Operation

whos(x)

Display value and data type for x.

islogical(x)

Return true if array is logical.

isa(x, 'logical')

Return true if array is logical.

class(x)

Return string with data type name.

cellfun('islogical', x)

Check each cell array element for logical.

Examples

Create a 3-by-6 array of logicals and use the whos function to identify the size, byte count, and class (i.e., data type) of the array.

rand('state',0);     % Initialize the state of the random number generator.
A = rand(3,6) > .5
A =
     1     0     0     0     1     0
     0     1     0     1     1     1
     1     1     1     1     0     1

whos A
  Name      Size            Bytes  Class      Attributes

  A         3x6                18  logical 

Find the class of each of these expressions:

B = logical(-2.8);  C = false;  D = 50>40;  E = isinteger(4.9);

whos B C D E
  Name      Size            Bytes  Class      Attributes

  B         1x1                 1  logical              
  C         1x1                 1  logical              
  D         1x1                 1  logical              
  E         1x1                 1  logical              

Display the class of A:

rand('state',0);     % Initialize the state of the random number generator.
A = rand(3,6) > .5

fprintf('A is a %s\n', class(A))
   A is a logical

Create cell array C and use islogical to identify the logical elements:

C = {1, 0, true, false, pi, A};
cellfun('islogical', C)
ans =
     0     0     1     1     0     1

Functions that Return a Logical Result

This table shows some of the MATLAB operations that return a logical true or false. Most mathematics operations are not supported on logical values.

Function

Operation

true, false

Setting value to true or false

logical

Numeric to logical conversion

& (and), | (or), ~ (not), xor, any, all

Logical operations

&&, ||

Short-circuit AND and OR

== (eq), ~= (ne), < (lt), > (gt), <= (le), >= (ge)

Relational operations

All is* functions, cellfun

Test operations

strcmp, strncmp, strcmpi, strncmpi

String comparisons

Examples

MATLAB functions that test the state of a variable or expression return a logical result:

A = isstrprop('abc123def', 'alpha')
A =
     1     1     1     0     0     0     1     1      1

Logical functions such as xor return a logical result:

xor([1 0 'ab' 2.4], [ 0 0 'ab', 0])
ans =
     1     0     0     1

Note however that the bitwise operators do not return a logical:

X = bitxor(3, 12);
whos X
  Name      Size            Bytes  Class     Attributes

  X         1x1                 8  double

String comparison functions also return a logical:

S = 'D:\matlab\mfiles\test19.m';
strncmp(S, 'D:\matlab', 9)
ans =
     1

Note the difference between the elementwise and short-circuit logical operators. Short-circuit operators, such as && and ||, test only as much of the input expression as necessary. In the second part of this example, it makes no difference that B is undefined because the state of A alone determines that the expression is false:

A = 0;
A & B
??? Undefined function or variable 'B'.

A && B
ans =
     0

One way of implementing an infinite loop is to use the while function along with the logical constant true:

while true
a = [];  b = [];
a = input('Enter username: ', 's');

   if ~isempty(a)
   b = input('Enter password: ', 's');
   end

   if ~isempty(b)
   disp 'Attempting to log in to account ...'
   break
   end
end

Using Logical Arrays 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:

str = input('Enter input string: ', 's');
if ~isempty(str) && ischar(str)
   sprintf('Input string is ''%s''', str)
end

Now run the code:

Enter input string: Hello
ans =
   Input string is 'Hello'

Using Logical Arrays in Indexing

A logical matrix provides a different type of array indexing in MATLAB. While most indices are numeric, indicating a certain row or column number, logical indices are positional. That is, it is the position of each 1 in the logical matrix that determines which array element is being referred to.

See Using Logicals in Array Indexing for more information on this subject.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS