0
0
MATLABdata~10 mins

Logical operators (&, |, ~) in MATLAB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Logical operators (&, |, ~)
Start with two logical values A and B
Apply AND (&) operator: A & B
Apply OR (|) operator: A | B
Apply NOT (~) operator: ~A or ~B
Get final logical results
End
Start with two logical values, then apply AND, OR, and NOT operators step-by-step to get logical results.
Execution Sample
MATLAB
A = [1 0 1];
B = [0 1 1];
C_and = A & B;
C_or = A | B;
C_not = ~A;
This code applies logical AND, OR, and NOT operators element-wise on arrays A and B.
Execution Table
StepOperationOperandsResult
1Initialize A[1 0 1]A = [1 0 1]
2Initialize B[0 1 1]B = [0 1 1]
3AND (&)A & B[0 0 1]
4OR (|)A | B[1 1 1]
5NOT (~)~A[0 1 0]
💡 All operations complete element-wise on arrays; logical results obtained.
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5
A[1 0 1][1 0 1][1 0 1][1 0 1]
B[0 1 1][0 1 1][0 1 1][0 1 1]
C_andN/A[0 0 1][0 0 1][0 0 1]
C_orN/AN/A[1 1 1][1 1 1]
C_notN/AN/AN/A[0 1 0]
Key Moments - 2 Insights
Why does the AND operation result in [0 0 1] when A is [1 0 1] and B is [0 1 1]?
Because AND (&) returns 1 only if both corresponding elements are 1. Here, only the last elements of A and B are both 1, so only the last result is 1 (see execution_table step 3).
What does the NOT (~) operator do to the array A?
The NOT (~) operator flips each element: 1 becomes 0, and 0 becomes 1. So ~A changes [1 0 1] to [0 1 0] as shown in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of the OR (|) operation at step 4?
A[1 1 1]
B[0 0 1]
C[0 1 0]
D[1 0 1]
💡 Hint
Check the 'Result' column in execution_table row for step 4.
At which step does the variable C_and get its value assigned?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Operation' column in execution_table where AND (&) is applied.
If A was [0 0 0], what would be the result of ~A according to the variable_tracker logic?
A[0 1 0]
B[1 1 1]
C[0 0 0]
D[1 0 1]
💡 Hint
NOT (~) flips each element; see variable_tracker row for C_not.
Concept Snapshot
Logical operators in MATLAB:
& (AND): true if both true
| (OR): true if any true
~ (NOT): flips true/false
Operate element-wise on arrays
Use for logical indexing and conditions
Full Transcript
This visual execution trace shows how MATLAB logical operators work on arrays. Starting with two arrays A and B, the AND operator (&) compares each element pair and returns 1 only if both are 1. The OR operator (|) returns 1 if either element is 1. The NOT operator (~) flips each element from 1 to 0 or 0 to 1. The execution table tracks each step and result, while the variable tracker shows how variables change. Key moments clarify why AND returns [0 0 1] and how NOT flips values. The quiz tests understanding of these steps and results.