what are logical operators in matlab

Matlab has three logical operators: AND(&), OR(|) and NOT(~). These operators are used to evaluate the Boolean expressions.

  • & operator is used for finding the logical AND of two expressions. It will return a matrix with logical 1 where both the input matrix have logical 1 otherwise a matrix with logical 0.

  • | operator is used for finding the logical OR of two expressions. It will return a matrix with logical 1 where either of the input matrix have logical 1.

  • ~ operator is used for finding the logical NOT of an expression. If the value of an element in the input matrix is zero, then after the NOT operation, that element value will be logical 1 and vice versa.

Here's an example to demonstrate how logical operators work in Matlab:

main.m
A = [1 0 1 0; 0 1 0 1];
B = [1 1 0 0; 0 1 1 0];

% Logical AND
C_and = A & B;

% Logical OR
C_or = A | B;

% Logical NOT
C_not = ~A;

disp('A:')
disp(A)

disp('B:')
disp(B)

disp('A & B:')
disp(C_and)

disp('A | B:')
disp(C_or)

disp('~A:')
disp(C_not)
253 chars
27 lines

Output:

main.m
A:
     1     0     1     0
     0     1     0     1

B:
     1     1     0     0
     0     1     1     0

A & B:
     1     0     0     0
     0     1     0     0

A | B:
     1     1     1     0
     0     1     1     1

~A:
     0     1     0     1
     1     0     1     0
278 chars
20 lines

related categories

gistlibby LogSnag