You are on page 1of 19

Computer Programming

(CSC209)
Lecture (11)
The switch and Roots of Polynomials

Dr.Omar Almutairi
The program design process (Rep)
1. Switch Expression and statement
Example
2. The try/catch Construct
Example
3. MATLAB Applications: Roots of Polynomials
Example
4. Polynomials Plot
Example
Conditional Statements (Branches)
If and switch statement

If Statement Switch Statement

4
Switch Expression
Example: Switch Statement
switch (12)
case {1,3,5,7,9}
disp('The value is odd.');
case {2,4,6,8,10}
disp('The value is even.');
otherwise
disp('The value is out of range.');
end
Example: Switch Statement
clear all
clc
n = 5;
switch (n)
case (1)
disp('January')
disp(first Month)
case (2)
disp('February')
disp(Scond Month)
case (3)
disp('March')
disp(Third Month)
otherwise
disp(not valid)
end
Example: Switch 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
The try/catch Construct
The try/catch construct is a special
form of branching construct designed
to trap errors.
Concept (try/catch)
Example (try/catch)
a = 2;
try
b=a*kk
catch
b=a*5
disp('very sorry this mistake')
end

b=
10.00
very sorry this mistake
MATLAB Applications: Roots of
Polynomials
A general polynomial is an equation of the form:

When n =3, the polynomial is a third-order equation


In general, a polynomial equation of nth order has n roots,

The function roots has the form


r = roots(p)
where p is an array
Example (roots)
Solve the equations to define (x) using roots
Example 4.7
Find the roots of the fourth-order
polynomial

Solution
» p = [1 2 1 -8 -
20];
» r = roots(p)
r=
2.0000 + 0.0000i
-1.0000 + 2.0000i
-1.0000 - 2.0000i
-2.0000 + 0.0000i 14
Plotting (plot ex 4.7)
x = [-3:0.05:3];
y = x.^4 + 2*x.^3 + x.^2 - 8*x -20;
plot(x,y)
grid on; 100

xlabel('x'); 80

ylabel('y'); 60

40
y

20

-20

-40
-3 -2 -1 0 1 2 3
x
Example: Polynomial Plotting
a = [9,-5,3,7];
x = -2:0.01:5;
f = polyval(a,x);
plot(x,f),xlabel('x'),ylabel('f(x)')
grid on;
1200

1000

800

600
f(x)

400

200

-200 16
-2 -1 0 1 2 3 4 5
x
17
Solution
• x=-5:0.1:5;
• y=(x-1).^2;
• plot(x,y)
• axis([-1 3 -1 3])
• grid on;
• xlabel('x');
• ylabel('y');
18
END

19

You might also like