Boolean Operators

In Matlab, like in C, any nonzero value is considered to be true and zero is false. Boolean operators will return 1 for true.

The boolean operators are:

Operator Name help
==is equal toeq
~=is not equal tone
<is less thanlt
<=is less than or equal tole
>is greater thangt
>=is greater than or equal toge
&andand
|oror
~not (unary)not

The not operator (~) converts zero entries in a matrix to 1 and all other entries to zero.

The boolean operation xor is implemented as a 2-variable function. xor(a, b) is equivalent to (a | b) - (a & b).

>> A = [-3:3; -2:4; -1:5]

A =

    -3    -2    -1     0     1     2     3
    -2    -1     0     1     2     3     4
    -1     0     1     2     3     4     5

>> ~A

ans =

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

With all other operators, if either argument is a scalar, the relational or logical operation is done with that scalar on each element. Otherwise, both matrices must have the same size and the operation is done element wise.

>> A == 4        % all entries equal to 4

ans =

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

>> A > 1         % all entries greater than 1

ans =

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

The easiest way to zero out all negative entries in a matrix is to multiply the result element wise with the original matrix:

>> (A >= 0) .* A        % all entries equal to 0


ans =

     0     0     0     0     1     2     3
     0     0     0     1     2     3     4
     0     0     1     2     3     4     5

>> (rand(size(A)) <= 0.75) .* A   % select approximately 75% of the entries of A (why?)
ans =

    -3     0    -1     0     1     0     0
    -2    -1     0     1     0     0     4
    -1     0     1     2     3     0     5

Logical Matrices

Each of these operators and functions returns a logical matrix. That is, islogical(ans) returns 1. A numeric matrix by default is not a logical matrix, but can be forced into one using the function logical.