Chapter 6
Chapter 6
Programming in
MATLAB
1
MATLAB
Ch 6
RELATIONAL OPERATOR
MATLAB
Ch 6
LOGICAL OPERATOR
MATLAB
Ch 6
Order of Precedence
Precedence Operation
1 (highest) Parentheses
2 Exponentiation
3 Logical NOT (~)
4 Multiplication, division
5 Addition, subtraction
6 Relational operators (>, <, >=, <=, = =, ~=)
7 Logical AND (&)
8 (lowest) Logical OR ( | )
MATLAB
Ch 3
Logical Built-in Functions
0
MATLAB
Ch 3
Logical Built-in Functions
MATLAB
Ch 3
Conditional Statement
MATLAB
❖ The if-end Structure Ch 3
1. Initialize a
2. Initialize x to a/2
3. Repeat 6 times (say)
Replace x by (x + a/x)/2
Display x
4. Stop.
a = 2;
x = a/2;
disp([’The approach to sqrt(a) for a = ’, num2str(a)])
for i = 1:6
x = (x + a / x) / 2;
disp( x )
end
disp( ’Matlab’’s value: ’ )
8
disp( sqrt(2) )
MATLAB
Eg. The if-end Structure Ch 3
n! = 1 × 2 × 3 × . . . × (n − 1) × n.
n = 10;
fact = 1;
for k = 1:n
fact = k * fact;
disp( [k fact] )
end
MATLAB
Ch 3
Conditional Statement
10
MATLAB
Ch 3
Conditional Statement
11
MATLAB
Ch 3
Eg. The if-elseif-else-end Structure
ME - 41019
disp( Grade D)
disp( Pass )
elseif Mark < 60
end
disp( Grade D)
elseif Mark < 80
disp( Grade D)
elseif Mark >= 80
disp( Grade A)
end
13
Ch 3
The switch-case Statement
14
MATLAB
The switch-case Statement
d = floor(10*rand);
switch d
case {2, 4, 6, 8}
disp( ’Even’ );
case {1, 3, 5, 7, 9}
disp( ’Odd’ );
otherwise
disp( ’Zero’ );
end
15
MATLAB
Ch 3
LOOPS
for k=1:3:10
x = k^2 16
end
MATLAB
Ch 3
LOOPS
x=1
while x<=15
x=2*x
17
end
MATLAB
Ch 3
NESTED LOOPS
18
MATLAB
Ch 3
THE break AND continue COMMANDS
for t = 0:2:100
height = 60 + 2.13*t^2 – 0.0013*t^4 + 0.000034*t^4.75*t;
if height < 0
break
end
end
fprintf (‘At %3d sec rocket altitude = %8.3f ft \n’, t, height)
19
MATLAB
20
MATLAB