You are on page 1of 14

MATLAB Notes for Mathematical Modeling (MA422)

Lia Vas
Content
1. Review of Matlab in Calculus 1
1.1 Basic arithmetic
1.2 Solving equations using solve
1.3 Reresenting functions
1.! "rahics
1.# Solving equations using fzero
1.$ %ifferentiation
1.& 'ntegration
1.( Limits
2. Review of Matlab in Calculus 2 an) 3
2.1 *arametric *lots
2.2 Secial effects
2.3 %erivatives of multivariable functions
2.! "rahing in +hree,%imensional Sace
3. %ifferential -quations
3.1 Basics of %ifferential -quations
3.2 .umerical Solutions
3.3 Secon) /r)er -quations 0*ractice roblems 11
!. M,2iles
!.1 Basic M,files
!.2 Branching an) Loos
0*ractice roblems 21
1. Review of Matlab in Calculus 1
1.1 Basic 3rithmetic
M3+L3B can )o an4thing 4our calculator can )o an) much more. 5ou can use 67 ,7 87 9 an) : to a))7
subtract7 multil47 )ivi)e or e;onentiate7 resectivel4. 2or e;amle if 4ou enter<
== 2:3 , 282
M3+L3B gives 4ou the answer< ans = 4
'f 4ou want to erform further calculations with the answer7 4ou can t4e ans rather than ret4ing the
whole answer. 2or e;amle7
>> srt(ans) ans = 2
+o erform s4mbolic calculations in M3+L3B7 use s!ms to )eclare the variables 4ou lan to use. 2or
e;amle7 suose that 4ou nee) factor x>,3x62. 2irst 4ou nee)
>> s!ms " 04ou are )eclaring that x is a variable1
, 1 ,
+hen7 for e;amle7 4ou can use the comman) factor.
>> factor("#2$%&"'2)
ans = ("$()&("$2)
.ote that we entere) %&" to reresent 3x in the comman) above. )ntering & for m*lti+lication is
al,a!s necessar! in MATLAB-
1.2 Solving -quations
2or solving equations7 4ou can use the comman) solve. +he comman) solve is alwa4s followe) b4
arenthesis. 3fter that7 4ou t4e the equation 4ou woul) li?e to solve in single quotes. +hen t4e
coma7 an) variable for which 4ou are solving in 0single1 quotes. +hus7 the comman) solve has the
following form
solve(.equation./ .variable for which you are solving.)
2or e;amle7 to solve the equation x@,2x,!7 4ou can use<
>> solve(."#%$2&"$4=0.)
an) get the following answer<
ans =
1 22
1 $('i2
1 $($i2
Aere i stan)s for the imaginar4 number
1 . +his answer tells us that there is Bust one real solution7
2.
M3+L3B can give 4ou both s4mbolic an) numerical answer. 2or e;amle7 to solve the equation 3x>,
(x62CD7 4ou can use
>> solve(.%&"#2$3&"'2=0./.".)
Matlab ro)uces the following ans =
1 44%'(4%&(0#((42)2 1 44%$(4%&(0#((42)2
'f we want to get the answer in the )ecimal form with7 sa47 three significant )igits7 we can use the
comman) v+a.
>> v+a(ans/ %)
ans = 1 2-%32 1 0-232
+he comman) v+a has the general form
v+a(expression you want to approximate/ number of significant digits)
5ou can solve more than one equation simultaneousl4. 2or e;amle suose that we nee) to solve
the s4stem x>6 x6 y> C 2 an) 2x-y C 2. Ee can use<
>> 1"/!2 =solve( ."#2' "' !#2 = 2./ .2&"$! = 2.)
to get the answer
" = 1 2452 1 (2
! = 1 $6452 1 02
.ote that the 1"/!2= art at the beginning of the comman) was necessar4 since without it M3+L3B
ro)uces the answer<
ans = "7 12"( s!m2 !7 12"( s!m2
+his answer tells us Bust that the solutions are two values of the air 0;741 but we )o not get the
, 2 ,
solutions themselves. +o get the solution vectors )isla4e)7 we must use 1"/!2= before the comman)
solve.
5ou can solve an equation in two variables for one of them. 2or e;amle the comman)
>> solve(.!#2$5&"&!$!'6&"#2'"=2./ .!.)
solves the given equation for values of y in terms of x. +he answer is<
ans = 1 %&"'22 1 2&"$(2
1.3 Reresenting a function
+he following table gives an overview of how most
commonl4 use) functions or e;ressions are reresente)
in M3+L3B.
+o reresent a function7 use the comman) inline. Similarl4
to solve7 this comman) is followe) b4 arenthesis an) has
the following form<
inline(.function./ .independent variable of the function.)
Aere is how to )efine the function x>63x,2<
>> f = inline(."#2'%&"$2./ .".)
f =
8nline f*nction7
f(") = "#2'%&"$2
3fter )efining a function7 we can evaluate it at a oint. 2or e;amle7
>> f(2)
ans = 3
'n some cases7 we will nee) to )efine function f as a vector. +hen we use<
>> f = inline(vectorize(."#2'%&"$2.)/ .".)
f = 8nline f*nction7
f(") = "-#2'%-&"$2
'n this case7 we can evaluate a function at more than one oint at the same time. 2or e;amle7 to
evaluate the above function at 17 3 an) # we have<
>> f(1( % 52)
ans = 2 (6 %3
'f a function is short7 it might be faster to eval*ate a f*nction at a +oint sim+l! 9! t!+ing the val*e
of x directl! for x. 2or e;amle7 to evaluate sin0x1 at xC27 siml4 t4e
>> sin(2) an) obtain the answer ans = -:0:2:;
3s when using the calculator7 one must be careful when reresenting a function. 2or e;amle

1
x x+6
shoul) be reresente) as (4("&("'6)) not as (4"&("'6) nor as (4"("'6)/

3
x
2
5x6
shoul) be reresente) as %4("#2'5&"'6) not as %4"#2'5&"'6/

e
5x
2
shoul) be reresente) as e"+(5&"#2) not as e#(5&"#2)/ e"+&(5&"#2)/ e"+(5"#2)
, 3 ,
f*nction or s!m9ol re+resentation in MATLAB
e:; e;0;1
ln ; log0;1
log ; log0;1Flog01D1
log. base a of ; log0;1Flog0a1
sin ; sin0;1
cos ; cos0;1
arctan0;1 atan0;1
G i
nor as e"+#(5&"#2)-
Ln0;1 shoul) be reresente) as log(")7 not ln(")-
log30;
2
1 shoul) be reresente) as log("#2)4log(%) not as
log(")4log(%)&"#2-
1.! "rahic
Let us start b4 )eclaring that x is a variable<
>> s!ms "
+he simlest comman) in M3+L3B for grahing is ez+lot. +he
comman) has the following form
ez+lot(function)
2or e;amle7 to grah the function x+x+17 4ou can use
>> ez+lot("#2'"'()
3 new win)ow will oen an) grah will be )isla4e). +o co4 the figure to a te;t file7 go to )dit an)
choose Co+! <ig*re. +hen lace cursor to the lace in the wor) file
where 4ou want the figure to be aste) an) choose )dit an) =aste.
Ee can secif4 the )ifferent scale on x an) y a;is.
+o )o this7 the comman) a"is is use).
't has the following form
a"is(1xmin, xmax, ymin, ymax2)
+his comman) arallels the comman)s in menu E'.%/E on the +'(3
calculators.
2or e;amle7 to see the above grah between ;,values ,1D an) 1D an)
4,values D an) $D7 4ou can enter
>> a"is(1$(0 (0 0 602)
.ote that the )omain of function )i) not change b4 comman) a;is. +o
see the grah on the entire )omain 0in this case H,1D7 1DI17 a)) that
)omain after the function in the comman) eJlot<
ez+lot(function/ 1xmin, xmax2)
'n this case7
>> ez+lot("#2'"'(/ 1$(0/ (02)
will give 4ou the )esire) grah.
2or the alternative comman) for grahics7 +lot/ 4ou can fin) more
)etails b4 t4ing hel+.
+o lot multile curves on the same win)ow7 4ou can also use the ez+lot comman). 2or e;amle<
>> ez+lot(sin("))
>> hold on
>> ez+lot(e"+($"#2))
, ! ,
,( ,$ ,! ,2 D 2 ! $ (
D
#
1D
1#
2D
2#
3D
3#
!D
!#
#D
;:26;61
,1D ,( ,$ ,! ,2 D 2 ! $ ( 1D
D
1D
2D
3D
!D
#D
$D
;:26;61
,1# ,1D ,# D # 1D 1#
D
1D
2D
3D
!D
#D
$D
;:26;61
>> hold off
1.# Solving equations using fzero
'n some cases7 the comman) solve ma4 fail to ro)uce all the solutions of an equation. 'n those
cases7 4ou can tr4 to fin) solutions using fzero 0short for Kfin) JeroK1 comman). 'n or)er to use the
comman)7 first 4ou nee) to write equation in the form
f(x)=.
+hus7 ut all the terms of th equations on one si)e leaving Bust Jero on the other. +o fin) a solution
near the x,value ;Ca7 4ou can use
fzero(.left side of the equation./ a)
+he comman) fzero7 similarl4 as solve is alwa4s followe) b4 arenthesis. +he equation shoul) be in
single quotes.
'f it is not clear what a convenient x,value a shoul) be7 4ou ma4 want to grah the function on the left
si)e of the equation first7 chec? where it intersects the x,a;is 0alternativel4 grah left an) right si)e of
the equation if it is not in f(x)= form an) see where the two functions intersect1 an) then )eci)e which
solution 4ou nee) to fin).
2or e;amle7 to solve the equation e
x!"
-"=x+#7 we can first grah the functions on the left an) right
si)e of the equation using
s!ms " ez+lot(e"+("#2)$2) hold on ez+lot("'4) hold off
2rom the grah7 we can see that the two functions intersect at a number near ,1 an) at a number near
1. +o use fzero7 we nee) to reresent the equation in the form e
x!"
-"-(x+#)= 0or simlifie) form e
x!"
,x-
$=1. +hen7 we can fin) the ositive solution b4 using fzero to fin) a Jero near 1 an) then to fin) the
negative solution near ,17 for e;amle. +hus7 both solutions can be obtaine) b4<
>> fzero(.e"+("#2)$2$("'4)./ $() ans = $(-243
>> fzero(.e"+("#2)$2$("'4)./ () ans = (-4(5
.ote also that the comman) solve(.e"+("#2)$2="'4./ .".) returns Bust the ositive solution. +hus7
?nowing how to use fzero comman) ma4 be reall4 useful in some cases.
1.$ %ifferentiation
Start b4 )eclaring ; for a variable. +he comman) for )ifferentiation is diff. 't has the following form
diff(function)
2or e;amle7
>> s!ms "
>> diff("#%$2&"'5)
gives us the answer ans = %&"#2$2
+o get n,th )erivative use
diff(function, n)
2or e;amle7 the 23r) )erivative of sin0;1 is obtaine) as follows.
>> diff(sin(")/ 2%) ans =$cos(")
1.& 'ntegration
, # ,
Ee can use M3+L3B for comuting both )efinite an) in)efinite integrals using the comman) int. 2or
the in)efinite integrals7 start with s!ms " followe) b4 the comman)
int(function)
2or e;amle7 the comman)
>> int("#2)
evaluates the integral an) gives us the answer ans = (4%&"#%
2or )efinitive integrals7 the comman) is
int(function, lower bound, upper bound)
2or e;amle7
>> int("#2/ 0/ ()
evaluates the integral +he answer is ans = (4%
'n M3+L3B 8nf stan)s for ositive infinit4. M3+L3B can evaluate the 0convergent1 imroer integrals
as well. 2or e;amle<
>> int((4"#2/ (/ 8nf) ans = (
2or the )ivergent integrals7 M3+L3B gives us the answer infinit4. 2or e;amle<
>> int((4"/ 0/ () ans = inf

1.( Limits
5ou can use limit to comute limits7 left an) right limits as well as infinite limits. 2or e;amle7 to
evaluate the limit when x L 2 of the function
x
2
4
x2
7 we have<
>> s!ms "
>> limit(("#2$4)4("$2)/ "/ 2) ans = 4
2or left or right limits<
>> limit(a9s(")4"/ "/ 0/ .left.) ans = $(
>> limit(a9s(")4"/ "/ 0/ .right.) ans = (
Limits at infinit4<
>> limit(e"+($"#2$5)'%/ "/ 8nf) ans = %
2. Review of the use of Matlab in Calculus 2 an) 3
2.1 *arametric *lots
Ee can use the comman) ez+lot to grah a arametric curve as well. 2or e;amle7 to grah a circle x
C cos t, y C sin t for D M t M 2%, we have<
>> ez+lot(.cos(t)./ .sin(t)./ 10/ 2&+i2)
2.2 Secial effects
5ou can change the title above the grah b4 using the comman) title. 2or e;amle7
>> ez+lot(."#2'2&"'(.)
>> title .a +ara9ola.
, $ ,
5ou can a)) labels to x an) y a;is b4 t4ing "la9el an) !la9el- 5ou can also a)) te;t to 4our icture.
2or e;amle7 suose that we want to a)) a little arrow ointing to the minimum of this function7 the
oint 0,17 D1. Ee can )o that with the comman)<
>> te"t($(/ 0/ .($(/ 0) >leftarro, a minim*m.)
2.3 %erivatives of Multivariable 2unctions
+he comman) diff can be use) to comute +artial derivatives. 2or e;amle7 to fin) the first artial
)erivative with resect to 4 of the function xy&7 use
>> s!ms " !
>> diff("#2&!#%/ !) ans = %&"#2&!#2
+o fin) the secon) artial )erivative with resect to x7 use
>> diff("#2&!#%/ "/ 2) ans = 2&!#%
2or the mi;e) secon) artial )erivative7 one can use<
>> diff( diff("#2&!#%/ ")/ !) ans = 6&"&!#2
2.! "rahing in +hree,%imensional Sace
+he comman) for )rawing 3% curves is ez+lot%. 2or e;amle7 suose that we nee) to grah the
heli; x C cos t, y C sin t, ' = t, for ,1D M t M 1D.
>> ez+lot%(.cos(t)./ .sin(t)./ .t./ 1$(0/ (02)
+here are two comman)s for grahing surfaces< ezmesh an) ezs*rf. +he first ro)uces a transarent
wire) lot7 a mesh surface. +he secon) ro)uces a sha)e)7 nontransarent surface. Both comman)s
can be use) for grahing surfaces that are given in the form ' = f(x, y)( 2or e;amle7 the grah of the
cone J C
x
2
+y
2
over the square ,& M x M &7 ,& M y M &7 can be obtaine) b4
ezmesh(.srt("#2'!#2)./ 1$;/ ;2/ 1$;/ ;2) or b4 ezs*rf(.srt("#2'!#2)./ 1$;/ ;2/ 1$;/ ;2)-
-Jmesh an) eJsurf are also use) when grahing the surfaces that are given in arametric form
x = f(s, t) y = g(s, t) ' = h(s, t)
+he cone J C
x
2
+y
2
can be reresente) b4 arametric equations as x = r cos t, y = r sin t, ' = r(
Nsing this reresentation7 we can get the grah b4 ezmesh(.r&cos(t)./ .r&sin(t)./ .r./ 10 / (0/ 0/ 2&+i2) or
b4 ezs*rf(.r&cos(t)./ .r&sin(t)./ .r./ 10 / (0/ 0/ 2&+i2)-
Ee can lot the vector fiel) <0x, y1 C )(x, y) i 6 O0;7 y) ? b4 using the comman) *iver("/ !/ =("/!)/
@("/!)). 2or e;amle7 we lot the vector fiel) <0x, y1 C x i , y ? as follows<
>> 1"/!2=meshgrid($(7-27(/ $(7-27()A
>> *iver("/ !/ "/ $!)A
>> a"is e*al
'n 3%7 we can also lot the vector fiel) <0x, y, '1 C )(x, y, ') i 6 O0;7 y, ') ? + *(x, y, ') B b4 using the
comman) *iver%("/ !/ z/ =("/!/z)/ @("/!/z)/ C("/!/z))- 2or e;amle7 we lot the fiel) <0x, y, '1 C x i 6
y ? + ' B as follows<
>> 1"/!/z2=meshgrid($%7(7%/ $%7(7%/ $%7(7%)A
>> *iver%("/ !/ z/ "/ !/ z)A
>> a"is e*al
, & ,
3. %ifferential -quations
3.1 Basics of %ifferential -quations
Ee can use M3+L3B to solve )ifferential equations. +he comman) for fin)ing the s4mbolic solution is
dsolve. 2or that comman)7 the )erivative of the function y is reresente) b4 D!. +he comman) has
the following form<
dsolve(.equation./ .independent variable.)
2or e;amle7 suose that we want to fin) the general sol*tion of the equation x y+ - y C 1. 5ou can
)o that b4< >> dsolve(."&D!$!=(./ .".) ans = $('"&C(
+his means that the solution is an4 function of the form y C ,16 cx7 where c is an4 constant.
'f we have the initial con)ition7 we can get the +artic*lar sol*tion on the following wa4<
dsolve(.equation./ .initial condition./ .independent variable.)
2or e;amle7 to solve x y+ - y C 1 with the initial con)ition y011C#7 we can use<
>> dsolve(."&D!$!=(./ .!(()=5./ .".) ans = $('6&"
+o grah this solution7 we can siml4 t4e<
>> ez+lot(ans)
Ee can grah a coule of )ifferent solutions on the
same chart b4 using hold on an) hold off
comman)s. 2or e;amle7 to grah the solutions of
)ifferential equation 4PCD.1401,41 for several )ifferent
initial con)itions7 40D1CD.17 40D1CD.3 40D1CD.# an)
40D1CD.&7 first fin) the four articular solutions7 then
grah them using hold on an) hold off comman)s.
+o observe the limiting behavior of the solution7 in
e;amles below the interval HD7 1DDI is use) as the
)omain.
2in)ing the four solutions<
>> dsolve(.D!=0-(&!&(($!)./.!(0)=0-(./ .".) ans = (4
((':&e"+($(4(0&"))
>> dsolve(.D!=0-(&!&(($!)./.!(0)=0-%. .".) ans = (4((';4%&e"+($(4(0&"))
>> dsolve(.D!=0-(&!&(($!)./.!(0)=0-5. .".) ans = (4(('e"+($(4(0&"))
>> dsolve(.D!=0-(&!&(($!)./.!(0)=0-;. .".) ans = (4(('%4;&e"+($(4(0&"))
"rahing the fours solutions<
>> ez+lot(.(4((':&e"+($(4(0&"))./10/(002) >> hold on
>> ez+lot(.(4((';4%&e"+($(4(0&"))./10/(002) >> ez+lot(.(4(('e"+($(4(0&"))./10/(002)
>> ez+lot(.(4(('%4;&e"+($(4(0&"))./10/(002) >> hold off
>>a"is(10/(00/0/(2)
3.2 .umerical Solutions
Man4 )ifferential equations cannot be solve) e;licitl4 in terms of elementar4 functions. for those
equations7 we will nee) the numerical metho)s to get the aro;imate solution. +he aro;imate
, ( ,
0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 1 0 0
0
0 . 1
0 . 2
0 . 3
0 . 4
0 . 5
0 . 6
0 . 7
0 . 8
0 . 9
1
t
1/ (1+3/7 e x p( -1/ 1 0 t) )
solutions of the equations can be foun) b4 using the comman) ode45.
Ee can illustrate the comman) o)e!# on the initial value roblem 4P C
e
x
2
7 40D1C1. +he comman)
o)e!# requires that the function on the right si)e of the equation is reresente) as a vector. So7 we
can start with the comman)< >> f=inline(vectorize(.e"+($"#2).)/."./.!.)A
+he comman) ode45 lots the grah of the initial value roblem on the secifie) interval. Suose
that we want to grah the solution on the interval HD7 2I. Ee use >> ode45(f/ 10 22/ () .ote that 1 at the
en) of the comman) reresents the y value at xCD from the given initial con)ition 40D1C1.
Ee can obtain the numerical values of the solution as well b4 using == 1"/ !2 = ode45(f/ 10 22/ ()- +he
values between D an) 2 at which ode45 calculates the solution are store) in x7 an) the value of
solution at these values is store) in y. +o obtain the grah of these values use >> +lot("/ !)-
3.3 Secon) /r)er -quations
+he secon) or)er linear equations can be solve) similarl4 as the first or)er )ifferential equations b4
using dsolve or ode45. 2or the comman) dsolve7 recall that we reresent the first )erivative of the
function y with D!. +he secon) )erivative of y is reresente) with D2!. 2or e;amle7 the comman) for
solving yPP,3yP62y C sin x.
>> dsolve(.D2!$%&D!'2&!=sin(")./ .".)
ans = %4(0&cos(")'(4(0&sin(")'C(&e"+(")'C2&e"+(2&")
'f we have the initial con)itions 40D1 C 1D7 4P0D1C,1D7 we woul) have<
>> dsolve(.D2!$%&D!'2&!=sin(")./ .!(0)=(./ .D!(0)=$(./ .".)
ans = %4(0&cos(")'(4(0&sin(")'542&e"+(")$:45&e"+(2&")
=ractice +ro9lems (
1. a1 2in) the general solution of the )ifferential equation y+-"y=$x.
b1 2in) the articular solution with initial con)ition 40D1C3.
c1 *lot the articular solution on interval HD72I an) fin) the value of this solution at 2.
2. "rah the solutions of the )ifferential equation y+ = x+y for the 4,values of the initial
con)ition 40D1 ta?ing integer values between ,2 an) !.
3. 2in) the general solution of the equation
yPP,! yP6! yC e
x
6x( +hen fin) the
articular solution with the initial values
y0D1C(7 yP0D1C3.
Eol*tions-
1. a1 "eneral solution< dsolve(.D!$2&!=6&"./ .".)
ans= ($6"$%)42'C(&e"+(2")
b1 *aticular solution< dsolve(.D!$2&!=6&"./
.!(0)=%./ .".) ans= ($6"$%':&e"+(2"))42
c1 s!ms " ez+lot(($6"$%':&e"+(2"))42/ 10 22)
+o fin) the value at 2< f=inline(($6"$
%':&e"+(2"))42/ ") f(2)
ans=2%3-(:
2. 2irst7 fin) the seven articular solutions of y+ =
x+y with initial con)itions 40D1C,27,17D7172737!.
s( = dsolve(.D! = "'!./ .!(0)=$2./ .".)
, Q ,
-1 0 1 2 3 4 5 6
-100
-80
-60
-40
-20
0
20
40
60
80
100
x
-1-x+5 exp(x)
s2 = dsolve(.D! = "'!./ .!(0)=$(./ .".) ... etc .. s; = dsolve(.D! = "'!./ .!(0)=4./ .".)
+hen lot them on the same grah. hold on ez+lot(s() ez+lot(s2) ...etc... ez+lot(s;)
hold off
3. >> dsolve(.D2!$4&D!'4&!=e"+(")'"#2./ .".)
ans = e"+(")'(44&"#2'(42&"'%43'C(&e"+(2&")'C2&e"+(2&")&"
>> dsolve(.D2!$4&D!'4&!=e"+(")'"#2./.!(0)=3./ .D!(0)=%./ .".)
ans = e"+(")'(44&"#2'(42&"'%43'5%43&e"+(2&")$4;44&e"+(2&")&"
!. M,files
!.1 Basics on M,files
Suose that 4ou want to erform the same oeration man4 times for )ifferent inut values. Matlab
allows 4ou to create a function or a scrit that 4ou can e;ecute reeate)l4 with )ifferent inut values
0i.e. to )o rogramming1. Such function or a scrit is calle) an M,file. 3n M,file is an or)inar4 te;t file
containing Matlab comman)s. 5ou can create them using an4 te;t e)itor that can save files as lain
03SC''1 te;t. 5ou can also create an M,file b4 using R2ileS menu an) choosing R.ew M,fileS otion from
4our Matlab comman) win)ow. 3n imortant fact to ?ee in min) when using M,files is that an M,file
can be e;ecute) from the comman) win)ow Bust if the KCurrent %irector4K on the to of the comman)
win)ow is set to be the same director! where the M,file is save).
)"am+le (- Suose that 4ou want to solve the equation ax + bx + c = D using the qua)ratic formula.
Ee can create a function which will have as inut values of a, b an) c an) which will give the
solution0s1 of the qua)ratic equation. Ee can enter the following in an M,file.
f*nction 1"( "22 = *adratic((a/ 9/ c)
"( = ($9'srt(9#2$4&a&c))4(2&a)A
"2 = ($9$srt(9#2$4&a&c))4(2&a)A
+o e;ecute the M,file an) fin) solutions of x ,3x 6 2 = D7 4ou can use
>> 1"(/ "22 = *adratic((/ $%/ 2)
+he outut is "( = 2 "2 = (
.ote that the semi,column s4mbol after the comman)s suresses )isla4 of the results of these
comman)s. +he values of ;1 an) ;2 will still be )isla4e) since we liste) these variables in the
brac?ets of the function.
3lternativel47 the following file can be use).
f*nction 1 2 = *adratic2(a/ 9/ c)
"( = ($9'srt(9#2$4&a&c))4(2&a)
"2 = ($9$srt(9#2$4&a&c))4(2&a)
Aere we )o not nee) to list the variables in the first line since we )i) not use the semi,column s4mbols
when comuting the values of ;1 an) ;2. 3lso7 4ou )o not nee) to list "( an) "2 in the first line since
the4 will be )isla4e) when 2n) an) 3r) lines are e;ecute). 3lso7 4ou can e;ecute this M,file to solve
x ,3x 6 2 = D siml4 as *adratic((/ $%/ 2) instea) of 1"(/ "22 = *adratic((/ $%/ 2) +he outut is the
same as for the first version.
== *adratic((/ $%/ 2)
+his means that 4ou want to solve the equation. Matlab gives 4ou the answers<
"( = 2 "2 = (
+hese M,files ro)uce the comle; values if the solutions of a qua)ratic equation are comle;
, 1D ,
numbers. 2or e;amle7 to solve x 6 ! = D7 we can use
>> *adratic((/ 0/ 4)
"( = 0 ' 2-0000i "2 = 0 $ 2-0000i
)"am+le 2. Suose that we nee) to write a rogram that calculates the Cartesian coor)inates (x,y)
of a oint given b4 olar coor)inates (r,,).
/ne ossible solution is the following M,file.
f*nction 1"/ !2 = +olar(r/ theta)
" = r&cos(theta)A
! = r&sin(theta)A
2or e;amle7 to calculate (x,y) coor)inates of for rC3 an) , = % , we can use the comman)
1"/!2=+olar(%/ +i) an) get the answer
" = $% ! = %-6;%:e$0(6
.ote that y is ver4 close to D. +he inaccurac4 comes from the fact that using +i for % in Matlab
gives an aro;imation of G not the e;act value. +he e;act reresentation of G is obtaine) b4
s!m(.+i.). +he comman) 1"/!2=+olar(%/ s!m(.+i.)) gives 4ou the e;ecte) answer
" = $% ! = 0.
!.2 Branching an) Loos
'n most cases7 the rograms cannot be re)uce) to a simle alication of a single formula. 'n those
cases7 we nee) to use branching or loos.
)"am+le %- Consi)er the following rogram that calculates the absolute value of a given number.
f*nction ! = a9sval(")
if " >= 0
!="A
else
!=$"A
end
2or e;amle7 the comman) !=a9sval($5) gives us the answer ! = 5.
+he revious e;amle e;hibits a rogram where a )ecision ma?ing is involve)< in certain case one
sequence of comman)s is erforme)7 in certain other cases the other sequence of comman)s is
erforme). +his is calle) 9ranching- +he simlest t4e of branching is with comman)s if -- else
0followe) b4 end1 Bust li?e in the above e;amle.
3nother situation that frequentl4 aears in rogramming is when a sequence of comman)s shoul) be
reeate) several times.
)"am+le 4- 2in) a sum of the series
n=1
100
1
n
2

'n or)er to fin) this sum7 it woul) be imractical to a)) 1DD numbers b4 han). +he basic i)ea that
coul) be use) in or)er to create a more ractical solution involves recursive reasoning< ?ee a))ing
1Fn:2 term at each ste to the sum comute) at revious ste. +his give us the following informal i)ea
for a rogram<
1. 3t the Jero,th ste7 the sum is D.
2. <or all nPs between 1 an) 1DD7 comute the sum at n,th ste b4 a))ing the term 1Fn:2 to the
sum of revious terms. 'f we )enote the sum of n,1 terms b4 s7 the sum of n terms will be
, 11 ,
s'(4n#2.
'n Matlab co)e7 this can be e;ecute) b4 using the comman) for n = (7(00 meaning that the variable
n is ta?ing integer values between 1 an) 1DD.
+he Matlab co)e for this is< s=0A for n=(7(00 s = s'(4n#2A end
+o )isla4 the final value of s7 siml4 t4e KsK.
)"am+le 5- "eneraliJe the i)ea from the revious e;amle to write a rogram that comutes the sum
of the first n terms of the sum f
i=1
n
1
i
2
or a given n.
+he main )ifference is that the value of n has to be secifie) as inut. +he i)ea is the same<
1. 3t the Jero,th ste7 the sum is D.
2. <or all iPs between 1 an) n7 if the sum of revious terms is s7 the sum of i terms will be
s'(4i#2.
Matlab co)e for this is<
f*nction s = series(n)
s=0A
for i=(7n
s = s'(4i#2A
end
2or e;amle7 the comman) s = series(20000) ro)uces s =(-644:.
)"am+le 6- Calculate the 0convergent1 sum
i=1

1
i
2
to first few )ecimals.
'n this case7 the for loo is not convenient to use since we )o not ?now how man4 terms we nee) to
a)) in or)er to obtain the require) accurac4. +he informal i)ea is the following
1. +he inut of the rogram is a small number e reresenting the require) accurac4.
2. Fhile the )ifference - of the sum of n+. an) the sum of n terms is greater than e7 ?ee
increasing the number of terms n(
3. % becomes smaller than the given small number7 aro;imate the infinite sum with the sum of
n terms.
Matlab co)e for this i)ea is<
f*nction 1s/ n2 = convGseries(e)
n=(A
+=0A 0Jero,th term of sum1
s=+'(A 0sum of the Jero,th an) the first terms1
,hile a9s(s$+)>e
n=n'(A 0number of stes is increase) b4 one1
+=sA 0n,th term of the sum becomes what n61
st
term was in revious ste1
s=+'(4n#2A 0n61
th
term is calculate)1
end
+he following e;amle is also a goo) ractice for mastering the i)ea of recursion.
)"am+le ;- Erite a rogram comuting the factoriel of a given ositive integer.
, 12 ,
'n or)er to obtain the algorithm7 it is helful to thin? of factoriel function
nT C 1 times 2 times 3 times ... times n
as of a recursive sequence<
1. 2actoriel011 C 1.
2. 2actoriel0n1 C 2actoriel0n,11 times n
+his i)ea transfers to the following Matlab function that calculates the factoriel of a given ositive
integer.
f*nction f = factoriel(n)
f=(A
for i=(7n
f=f&iA
end
2or e;amle7 the comman) f = factoriel(6) ro)uces the outut f = ;20.
'n M3+L3B 4ou can reference one rogram within another.
)"am+le 3- 3ro;imate the number e b4 the first n terms of the following series e=

n=0

1
n!
Since the formula for the n,th term of the series has factoriel in it7 this rogram requires the use of the
function factoriel from the revious e;amle. +his is one ossible realiJation of this i)ea.
f*nction e = nat*ral(n)
e=(A
for i=(7n
e=e'(4factoriel(i)A
end
+he comman) e = nat*ral(40) ro)uces the outut e =2-;(3%.
=ractice +ro9lems 2
1. +he number G can be calculate) using the following formula<
Erite rograms that<
a1 3ro;imates G with the first 1DDD terms of the above sum.
b1 3ro;imates G with the first n terms of the above sum7 for given n.
c1 3ro;imates G using the above sum to three )ecimals.
2. Consi)er the recursive sequence a(n+.) = with an initial con)ition a()=.
Erite a rogram that comuter the n,th term for a given value of n. -;ecuting the rogram for
nC1DD7 1DDD an) 1D7DDD comute the limit of this sequence to first few )ecimals.
3. 2or a given n7 calculate the n,th term of the sequence a(n+.)= ./(.+a(n)) with initial con)ition
a(.)=.. Nse that rogram to )etermine the limit of this sequence.
!. +o aro;imate the integral 0a
b
f(x) dx , we can use the left sum with n subintervals. 'n this case7
we are a))ing the areas of rectangles of height f(x1i) for i=,(((, n-. an)
of the wi)th h=(b-a)/n.
2(n) C h times f(x1) 6 h times f(x1.) 6 ... 6 h times f(x1n-.).
+o formaliJe this i)ea7 it is again useful to thin? of the above formula for 2 in a recursive form
1. 2(x1) = h times f(x1),
2. 2(i+.) = 2(i) + h times f(x1i).
Erite a Matlab function that aro;imates a )efinite integral using left sum. Ehen e;ecuting
, 13 ,
the rogram7 4ou will nee) to inline the function f first. +est 4our rogram b4 evaluating the
integral from D to 1 of ;:2 using 1DDD subintervals. 5ou shoul) obtain D.33. 3)at the rogram
to calculate the Right Sum.
#. Nsing the if--- else comman)7 write a function that calculates the solution of qua)ratic equation
if real solutions e;ist an) has the te;t K.o real solutionK for outut otherwise. +o )isla4 te;t7
4ou can use the comman) dis+(H---H) with te;t that 4ou want )isla4e) between the quotes.
Eol*tions
1. a1 +=(A for n=(7(000 +=+'4&($()#n4(2&n'()A end +
b1 f*nction + = seriesGs*m(n) +=( for i=(7n += +'4&($()#i4(2&i'()A end
c1 f*nction +=seriesGs*m2(e)
n=(A +=(A 0Jero,th term of sum1 s=+$44%A 0sum of the Jero,th an) the first terms1
,hile a9s(s$+)>e
n=n'(A 0number of stes is increase) b4 one1
+=sA 0n,th term of the sum becomes what n61
st
term was in revious ste1
s=+'4&($()#n4(2&n'()A 0n61
th
term is calculate)1
end
2. f*nction a = rec*rsiveGse*ence(n) a=0 for i=(7n a= srt(2'a)A end
+he limit of this sequence is 2.
3. f*nction a = rec*rsiveGse*ence(n) a=( for i=(7n a= (4(('a)A end
+he limit of this sequence is D.$2.
!. f*nction L=leftGs*m(f/a/9/n)
h=(9$a)4(n)A
L=h&f(a)A
for i=(7n$(
L=L'h&f(a'h&i)A
end
+o test the rogram7 use f=inline(."#2./ .".) an) L=leftGs*m(f/ 0/ (/ (000). "et LCD.333.
2or the right sum7 4ou can use
f*nction C=rightGs*m(f/a/9/n)
h=(9$a)4(n)A
C=h&f(a'h)A
for i=27n
C=C'h&f(a'h&i)A
end
#. f*nction 1 2 = *adratic(a/ 9/ c)
D=9#2$4&a&cA
if DI0 dis+(.No real sol*tions.)
else "( = ($9'srt(D))4(2&a) "2 = ($9$srt(D))4(2&a)
end
, 1! ,

You might also like