Академический Документы
Профессиональный Документы
Культура Документы
CHEG 220
Week_3_Lec_1
Programming with MATLAB
Previously in CHEG220
Structured MATLAB Programs
Top-down Structure
Built-in and user-defined Functions
Outline
~
&
|
&&
||
NOT
AND
OR
Short circuit AND
Short circuit OR
Examples
1- A[1,0,1]. ~A[0,1,0]
2- A[1,0,1], B[0,0,1]. A & B = C[0,0,1]
3- A[1,0,1], B[0,0,1]. A | B = C[1,0,1]
Examples
x[0,3,9], y[14,-2,9] z=~x , z[1,0,0]
u=~x>y, u[0,1,0]
v=~(x>y), v[1,0,1]
z =[5,-3,0,0]&[2,4,0,5] z=[1,1,0,0]
x[6,3,9] ,y[14,2,9], a[4,3,12],z=(x>y)&a, z[0,1,0]
z =[5,-3,0,0]|[2,4,0,5] z=[1,1,0,1]
Table of truth
x
y
~x
x|y
x&y
xor (x,y)
true true false true
true
false
True false false true
false
true
false true true true
false
true
false false true false
false
false
find Function
The function find(x) computes an array containing the
indices of the nonzero elements of the array x
Example: x=[5,-3,0,0,8]; y[2,4,0,5,7]
z=find[x&y] z=[1,2,5]
Conditional statements(1)
Conditional statements(2)
The if statement
if logical expression
statements
end
if x >= 0
y = sqrt(x)
end
Conditional statements(3)
Another example
z=0;w=0;
if (x>=0)&(y>=0)
z=sqrt(x)+sqrt(y)
w=log(x)-3*log(y)
end
Conditional statements(4)
Nested if statements
if logical expression 1
statement group 1
if logical expression 2
statement group 2
end
end
if x<0
y=abs(x)
if y>4
z=sqrt(y)
end
end
Conditional statements(7)
if logical expression 1
if logical expression 2
statements
end
end
The if statement
if logical expression 1 & logical expression 2
statements
end
Conditional statements(5)
Flowchart
x
x<0?
false
true
y=abs(x)
y>4?
true
z=sqrt(y)
End
false
Conditional statements(6)
if x >= 0
y = sqrt(x)
else
y=exp(x)-1
end
Conditional statements(8)
The else statement
start
Logical
Expression
False
True
Statement Group 1
End
Statement Group 2
Conditional statements(9)
if x >= 5
y = log(x)
elseif x>=0
y=sqrt(x)
else
y=exp(x)-1
end
Conditional statements(10)
Start
Logical
Expression 1
True
Logical
Expression 1
False
Statement
Group 1
True
Statement
Group 2
End
Statement
Group 3
Conditional statements(12)
flowchart
No
x>10
Yes
y=5x
z=7x
y=log(x)
No
y3?
Yes
z=4y
y2.5?
Yes
z=0
z=2y
y,z
No
Conditional statements(11)
The program describing the flowchart on the last slide :
if x > 10
y=log(x)
if y >= 3
z=4*y
elseif y >= 2.5
z=2*y
else
z=0
end
else
y=5*x
z=7*x
end