# Matlab boolean operators

## Get Matlab Help Now..!

In Matlab, basically there are four boolean operators:

 & logical AND | or(A,B) ~ logical NOT (complement) Xor exclusive OR

These operators makes vectors or matrices of the same size as the operands, with 1 when the condition is true, and 0 when the condition is false.

The not operator (~) changes zero entries in a matrix to 1 and all other entries to zero.
The boolean operation xor is applied as a 2-variable function. xor(a, b) is equal to (a | b) - (a & b).

Along with the four basic operators there are other inequality operators

Operator Name
== is equal to
~= is not equal to
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to

Better understanding of Boolean operators can be developed by looking at below written examples:

>> 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 in MATLAB, if argument is a scalar, the relational or logical operation is done with that scalar on each element. Otherwise, both matrices will have the same size and the operation is done element wise order.

>> A == 4 % all entries is 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 is 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 easy way to zero from all negative entries in a matrix is to multiply the result element wise with the original matrix:

>> (A >= 0) .* A % all entries is 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 % to select 75% of the entries of A

ans =

-3 0 -1 0 1 0 0

-2 -1 0 1 0 0 4

-1 0 1 2 3 0 5