0
0
MATLABdata~5 mins

Logical operators (&, |, ~) in MATLAB

Choose your learning style9 modes available
Introduction

Logical operators help you check if conditions are true or false. They let you combine or change these true/false values easily.

When you want to check if two things are both true at the same time.
When you want to see if at least one of several things is true.
When you want to flip a true to false or false to true.
When you need to filter data based on multiple conditions.
When you want to control the flow of your program based on combined conditions.
Syntax
MATLAB
A & B  % Logical AND: true if both A and B are true
A | B  % Logical OR: true if A or B (or both) are true
~A     % Logical NOT: true if A is false, false if A is true

Use & to check if both conditions are true.

Use | to check if at least one condition is true.

Examples
This checks if x is greater than 0 AND y is greater than 5. Both are true, so result is true (1).
MATLAB
x = 5;
y = 10;
result = (x > 0) & (y > 5);
This checks if a is greater than 5 OR b is greater than 5. a is false, b is true, so result is true (1).
MATLAB
a = 3;
b = 7;
result = (a > 5) | (b > 5);
This flips the value of flag. Since flag is true, result becomes false (0).
MATLAB
flag = true;
result = ~flag;
Sample Program

This program uses logical AND, OR, and NOT to compare numbers and prints the results as 1 (true) or 0 (false).

MATLAB
x = 8;
y = 3;

% Check if x is greater than 5 AND y is less than 5
and_result = (x > 5) & (y < 5);

% Check if x is less than 5 OR y is less than 5
or_result = (x < 5) | (y < 5);

% Flip the value of and_result
not_result = ~and_result;

fprintf('AND result: %d\n', and_result);
fprintf('OR result: %d\n', or_result);
fprintf('NOT result: %d\n', not_result);
OutputSuccess
Important Notes

Logical operators return 1 for true and 0 for false in MATLAB.

Use parentheses to group conditions clearly.

Logical NOT (~) only needs one input and flips its truth value.

Summary

Use & to check if both conditions are true.

Use | to check if at least one condition is true.

Use ~ to flip true to false or false to true.