Determine if Arrays Are Logical

To determine whether an array is logical, you can test the entire array or each element individually. This is useful when you want to confirm the output data type of a function.

This page shows several ways to determine if an array is logical.

Identify Logical Matrix

Create a 3-by-6 matrix and locate all elements greater than 0.5.

A = gallery('uniformdata',[3,6],0) > 0.5
A =

     1     0     0     0     1     0
     0     1     0     1     1     1
     1     1     1     1     0     1

The result, A, is a 3-by-6 logical matrix.

Use the whos function to confirm the size, byte count, and class (or data type) of the matrix, A.

whos A
Name      Size            Bytes  Class      Attributes

  A         3x6                18  logical  

The result confirms that A is a 3-by-6 logical matrix.

Test an Entire Array

Use the islogical function to test whether A is logical.

islogical(A)
ans =

     1

The result is logical 1 (true).

Use the class function to display a string with the class name of A.

class(A)
ans =

logical

The result confirms that A is logical.

Test Each Array Element

Create a cell array, C, and use the 'islogical' option of the cellfun function to identify which cells contain logical values.

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

     0     0     1     1     0     1

The result is a logical array of the same size as C.

To test each element in a numeric matrix, use the arrayfun function.

arrayfun(@islogical,A)
ans =

     1     1     1     1     1     1
     1     1     1     1     1     1
     1     1     1     1     1     1

The result is a matrix of logical values of the same size as A. arrayfun(@islogical,A) always returns a matrix of all logical 1 (true) or logical 0 (false) values.

Summary Table

Use these MATLAB® functions to determine if an array is logical.

Function SyntaxOutput SizeDescription
whos(A)N/ADisplays the name, size, storage bytes, class, and attributes of variable A.
islogical(A)scalarReturns logical 1 (true) if A is a logical array; otherwise, it returns logical 0 (false). The result is the same as using isa(A,'logical').
isa(A,'logical')scalarReturns logical 1 (true) if A is a logical array; otherwise, it returns logical 0 (false). The result is the same as using islogical(A).
class(A)single stringReturns a string with the name of the class of variable A.
cellfun('islogical',A)Array of the same size as AFor cell arrays only. Returns logical 1 (true) for each cell that contains a logical array; otherwise, it returns logical 0 (false).
arrayfun(@islogical,A)Array of the same size as AReturns an array of logical 1 (true) values if A is logical; otherwise, it returns an array of logical 0 (false) values.

See Also

| | | | |

Was this topic helpful?