Class 3
Class 3
CSS
Loops:
A loop specifies that a command or group of commands should be repeated several times.
(1) For loop: The easiest way to create a loop is to use a for statement,
8.2 1. 0
Here is a simple examplethat computes and displays 10!= 10. 9
»f=1;
>>for n=2:10
f-fn;
end
>>f
f
3628800
The ioop begins with the for statement and ends with the end statement. The command between
those statements is executed total of nine times, once for each valuc of n from 2 to
a
semicolon to suppress intermediate 10. We used a
to type f after the end of the
output within the Joop. To see the final output, we then needed
loop. Without the semicolon, MATLAB would display each of the
intermediate values 2!, 3!,....
We have presented the loop above as you might type it into an M-file;
MATLAB, but it helps human readers indentation is not required by
commands above directly to the distinguish the commands within the
loop. If you type the
for statement. You should MATLAB prompt, you will not see a new prompt after entering the
continue typing, and after you enter the end
evaluate the entire loop and
display a new prompt. statement, MATLAB wil
(2) While loop: Here is a simple example of a
infinite series + script M-file that uses while to numerically sum the
, stopping only when the terms become so small
machine precision) that the
numerical sum stops changing. (comipared to the
>>n = 1;
> oldsum =
-1;
>> newsum =
0;
>> while newsum > oldsum
oldsum newsum;
newsum = newsum +n(-4);
n=n +1;
end
>> newsum
newsum=
1.0823
add n'(-4) to newsum,
Here initialize newsum to 0 and n to 1, and in the loop we successively
we
track of how much newsum
1 to n, and repeat. The purposé of the variable oldsum is to keep
add iteration to the next. Each time MATLAB reaches the
end of the loop, it starts over
changes from one in the while statement isS
again at tne while statement. If newsum exceeds oldsum, the expression
which will happen
true, and the loop is executed again. But the first time the expression false,
is
statement and executes the next
wnen newsum and oldsum are equal, MATLAB skips to the end
line, which displays the final value of newsum (the result is 1.0823 to five significant digits), Tne
initial value of-1 that we gave to oldsum is somewhat arbitrary, but it must be negative so that the
first timethe while statement is executed, the expression therein is true; if we set oldsum to
initialiy, then MATLAB would skip to the end statement without ever running the commands in the
ioop.
One more example which display natural nunbers îrom 1to 10 by using while statement id shown
below, by using 'disp' function wlich displays variable values and string constants..
>>j=l;
>>while(i<10)
disp(i)
i=i+1;
end
2
If-else-end:
For a simpleillustration of branching withif, consider the following function
M-file absval.m, which computes the absolute value ofa real number:
function y absval(x)
if x = 0
else
y -XX;
end
The first line of this M-file states that the function has a single input x and a single output y.
If the input x is nonnegative, the if statement is determined by MATLAB to be true.
Then the command between theifand the else statements is executed to set y equal to x,
while MATLAB skipsthe command between the elseand end staternents. However,
ifx is negative then MATLAB skips to the else statement and executes the succeeding command
setting yequal to -x.
one more simple example, which narrateshow to use ifstatement is given below
>a=1;
>> if{a==1))
disp('am gud')
else
dispCambad).
endi
output of above coding will be
am gud (as a value is 1)
where 'disp' is a function which displays any variable or text string.
Sometimes you may. want MATLAB to junp out of a for loop prematurely, for examnple if, a
certain condition is met. Or, in a while loop, there may be an auxiliary condition that you want to
check in addition to the main condition in the while statement. Inside either type of loop, you can
use the command break to tell MATLAB to stop running the loop and skip to the next line after the
end of the loop, The command break is generally used in coijunctiòn with an if statement. The
following script M-file computes the same sum as in the previous exampie, except that it places an
explicit upper limit on the number of iterations.
>>newsum= 0
>>for n 1:100000
oldsum-newsum;
newsum newsum + n°(-4);
i f news um = oldsum
break
end
end
newsum
switch: cases
allows you to
branch among several
ne asother
main branching command is switch. It must be described through equalities
as between two cases, thoughthe cases
Just easily between three cases
Here is simpleexample, which distinguishes
rather than inequalities.
for the input:
a
Here the switch statement evaluates the input x and then execution of the M-file skips to
whichever case statement has the same value. Thus if the input x equals 1, then the output
yis set to bethe string 'one', while if x is 2, then y is set to 'two'. In each case, once MATIAB
encounters another case statement or since an otherwise statement, it skips to the tend
statement, so thatat most one case is executed. If no match is found among the case
statements, then MATLAB skips to the (optionai) otherwise statement, or else to the end
statement. In the exampie above, because of the otherwise statement, the output is "hany'
if the input is not 1 or 2.
Note: Unlike if, the command switch does rot allow vector expressions, but
it does allow
strings. Type help switch to see an cxample using strings. This feature can be
useful if you
want to deaign a function M-file that uses a string
input argument to select among several
dilferent variants of a program you write.
A
JAS :3
statements
Exerciseonconditional
of first 10 natural numbers using for loop.
1. Find sum
for loop.
100 natural numbers using
2. Find sum of first for loop.
of of first 3 natural numbers using
3. Find sum squares
for loop.
Find of squares of first 10 natural numbers using
4. sum
for loop.
50 natural numbers using
5. Find sum of cubes of first
100 natural numbers using for loop.
6. Find sum of cubes of first
numbers using while loop.
7. Find sum of first 10 natural
8. Find sum of reciprocals of first
5 natural numbers using while loop.
9. Print your name 10 times using
for loop.
100 using while loop.
10. Print even numbers between 1 to
11. Print multiples of 3 between 1 to 300.
'Polynomlalsin Matlab
are the
vector in which the elements
A polynomial is Represented by a row
coefficients.
Must include all coefficients, even if 0
Examples
8x+5 p=[8 5]
6x2-150 h= [6 0-150
Value of a Polynomial
Matlab can also compute the value of a polynomial at point x using a function,
which is sometimes more convenient
polyval (p. x)
Where pis a vector with the coefficients of the polynomial
x is a number, variable or expression
-
53
Roots of a Polynomial
.Matlab can compute the roots of a function
r= roots(p)
Wheer-p is a row.vector with the coefficients of the polynomial
-ris a column vector with the roots of the polynomial
Ex:f(x)=x2-2x -3
p [1-2-3]:
r= roots(p)
r
3.0000
1.0000
Polynomial Coefficients
Given the roots of a polynomial, Matlab can compute the coefficients
ppolyT)
Where- ris a row or column vector with the roots of the polynomial
- pis a row vector with the coefficients
Ex: roots = -3, +2
r=[-3 +2]:
P poly(r)
P
11-6
Adding and Subtracting Polynomials
Can dothisin Matlab by just addingg or subtracting the coefficient vectors
Where- Both vectors must be of the same size, so the shorter vector must be
padded with ~eros
Ex:f(x) = 3x + 15x5 10x3 -3x2 +15x - 40
Sx) = 3x3-2x-6
p1 [3 150-10-3 15-40];
p2 [00030-2-6];
p pl+p2
P
3 15 0-7-3 13-46
Multiplying Polynomials .
Matlab can also multiply polynomials
CWhere-a
Conva,and
b) b are the vectors of the coefficients of the functions being multiplied
- cis the vector of the coefficients of the product
Ex:(2x +x-3) (x+1)
a =[21-3]:
b [11
cconva, b)
C
23-2-3
Dividing Polynomials
Matlab can also divide polynomials
[q.r) deconv(u,v)
Wliere-u is the coeficient vector ofthe numerator
- Vis the coefticient vector ofthe denominator
-qis the coefficient vector of the quotient
-
ris the coefficient vector ofthe remainder
Ex: (x2 9x 10)(x +1)
-
u [1-9-10];
V[11];
[q. r] deconv(u,v)
1-10 %quotient is (x: 10)
r
000 % remainder is 0
Derivatives of Polynomials
Matlab can also calculate the derivatives
of polynomials
k=
polyaerpnofficient vector
Where p is the coefficient vector of the solynomiai
kis the coefficient vector of the derivative
- rolynoa
Ex:(3x2-2x+4)
p [3-2 4];
k polyder(p)
k
6-2
% dy/dx= 6x - 2
Integrals of Polynomials
Matlab can also calculate the integral of a polynomial
8 polyint([h, k)
where h is the coefficient vector ofthe polynomial
g is the coefficient vector ofthe integral
kis the constant ofintegration- assumed to be 0 if not present
Ex:J6xdz
h [60 0];
8 polyint(h)
g
2000
AP
EXERCISEOF POLYNOMIALS(CLASS 3)
for given X
(A) Find value of given polynomials
4,x 2.1 to 2.3.
(1)5x+4x3+ 2x2 + 7x = =
(9)2x + 3r3+5x + 2x =
4,x =-2.3 to -
2.1
(10)2x +3x3+x2+5x =
3,x = -2.1 to -
1.9.
(1)2x+3r3 + 12+2x =2
(2)x+2x3+ 3x24x =3.
(3) 3x+x3 + 4x2 +x = 1
(4)9x +2x3 +
x2 +x =5
(5) 6x+x3 +x2+ x = 1
(6)x +2x3+x2 +x = 9
(7) 2x + x3 + 3x2+x = 1
(9) x+6x3 + x + x = 2
(1)x-3 and x - 5x2 10x - 6
(2)x-1and x3 -
1
(1)-5x2 10x -6
(2)x-1
(3)x-3x3+x-3x-2
(4) 3x3 16x + 23x - 6
(5)3x3+2x* 19x +6
(6)3x3 26x2+52x- 24
(7) 3x3 16x2+23x -6
(8) 3x2+2r3 - 19x +6
TIT