You are on page 1of 19

Computer Programming

(CSC209)
Lecture (9)
Logical Statements and MATLAB
Operators
Dr.Omar Almutairi
Agenda

❖ What is a logical statement?

❖ How MATLAB handles Logical values

❖ Logical operators

❖ Using logical operators to test truth values of

statement
Top-Down Design Process
Large Task
Smaller
SubTask
SubTask SubTask

Smaller
SubTask

3
Build MATLAB script functions
The program design process
1. State problem
2. Define Inputs & Outputs
3. Design Algorithm of Steps
4. Turn Algorithm into MATLAB statements
5. Test

2-26
The program design process
Programming with MATLAB

6
True / False Operators
Relational

Something we must know

True 1

False 0
7
Examples

Element by Element comparison for matrix relationship


Logical and Scalar Operator
Logical Operator (Matrix)

Scalar Operator (Number)


Logical Operation with Matrix
Example:
>> b = [1 3 -4 4 -7 9 8 2];
>> a = [1 0 1 0 0 1 0 1]
>> k = b>4
k=
0 0 0 0 0 1 1 0
>> c = b(logical(a))
c=
1.00 -4.00 9.00 2.00
Logical Operation with Matrix
Example:
>> a=‘omar'
k=
omar
>> a == ‘omar'
ans =
1 1 1 1
Logical Exclusive or (xor)
xor(S,T) is the logical symmetric difference of
elements S and T:
TRUE = where either S or T, but not both, is nonzero.
FALSE = where S and T are both zero or nonzero.
>> xor(1,0)
ans =
1
>> xor(1,5)
ans =
0
>> xor(0,0)
ans =
0 12
Truth Table for Logical Operator

0 0 0 0 0 1
0 0 1 1 1 1
0 0 1 1 1 0
1 1 1 1 0 0
Examples
Assume that the following variables are initialized with
the values shown and calculate, the result of the
specified expressions:
value1 = 1
value2 = 0
value3 = 2
value4 = -10
value5 = 0
value6 = [1 2; 0 1]
The questions related to this example will be attached later

14
Examples
(a) ~value1
(b) ~value3
(c) value1 | value2
(d) value1 & value2
(e) value4 & value5
(f) ~(value4 & value5)
(g) value1 + value4
(h) value1 + (~value4)
(i) value3 && value6
(j) value3 & value6

15
Examples
1- value3>value1
2- value3>value1 && value1>value2
3- value3>value1 && value1>7
4- value3>value1 || value1>7
5- value3>value1 && value1>7 || 6>7

16
Selected MATLAB Logical function

17
Practice

18
END

19

You might also like