Anda di halaman 1dari 5

12/20/2015

SolutionofEquationsusingMATLAB

W.R.Wilcox,ClarksonUniversity
LastrevisedMay13,2010

SOLUTIONOFEQUATIONSUSINGMATLAB

Seealso:
TutorialonsymbolicmathematicsusingMATLAB
Relationshipsbetweenmathematical,MATLABandExcelexpressions
MATLABtutorialsonanalysisandplottingofdata
Commonconversionfactorsforunits
Introductory MATLAB tutorials: See MATLAB help, MATLAB, getting started. The
following sites also have useful tutorials: Mathworks, Florida, Louisiana, New Hampshire,
CarnegieMellon

The present tutorial deals exclusively with numerical methods of solving algebraic and
trigonometric equations, both single and several simultaneously, both linear and nonlinear.
Analyticalsolutionscanbeobtainedusingthemethodsdescribedinthesymbolictutorial.When
bothsymbolicandnumericalmethodswork,sometimesoneissimplerandsometimestheother.

Inordertobenefitfromthefollowingmaterialonemustcopyandpastetheindicatedcommands
into MATLAB and execute them. These commands are shown in the format >> help plot, for
example.TheusershouldlookupeachcommandinMATLAB'shelpinordertounderstandthe
commandandthedifferentpossiblesyntaxesthatcanbeusedwithit.

Graphicalsolutionofonenonlinearequationortwononlinearequationsinexplicit
form

When a single equation or a pair of equations is to be solved, it is good practice to first make a
plot.Inthisway,itcanbeseenimmediatelywhattheapproximatesolutionis.

Inordertoplotanequationusingthe"plot"commanditmustbeintheexplicitform,i.e.y=f(x).
Iftheequationcanbewrittenonlyinimplicitform,i.e.f(x,y)=0,thenthe"ezplot"commandmust
beusedasdescribedinthesymbolictutorial.

Weconsiderfirstasingleequation,i.e.f(x)=0.Asanexamplewewillusesin2(x)ex/21=0.Do
thefollowingsteps:
1. Whileoptional,it'sagoodideatocleartheWorkspacememoryinordertoavoidthechance
ofMATLABusingapreviousvalueforavariable:
>>clear
2. Guesstherangeofxvaluesoverwhichyouexpectasolutionandgeneratevaluesforthe x
vector over this range. Select an increment small enough to yield a smooth curve. For
example:
>>x=10:0.01:10
givesxfrom10to+10inincrementsof0.01.
3. Generatethey=f(x)vectorcorrespondingtothesexvalues:
>>y=sin(x).^2.*exp(x/2)1
Noticethedotsbefore^and*.Thesedotsareessential.Becausexisavector,wemustuse
arrayoperationsratherthanscalaroperations(withoutthedot).
http://people.clarkson.edu/~wwilcox/ES100/eqsolve.htm

1/5

12/20/2015

SolutionofEquationsusingMATLAB

4. Also create a line for y = 0. The intersection of this line with the curve above gives the
solution (or solutions, as in this example). To do this we create a vector with the same
numberofvaluesasx,witheachvaluebeing0.
>>y0=zeros(1,length(x))
5. Maketheplot:
>>plot(x,y,x,y0)
6. Locatethesolution(s).Ifthetwolinesdonotintersect,repeatwithanotherrangeforx.In
our example, the lines intersect more than once, and we surmise, in fact, that there are
infinitelymanysolutionsfornegativex.Letusselectthesolutionataboutx=1.Enlarge
thisareaoftheintersectionintheFigurewindowbyTools/ZoomIn,andthenclickingnear
theintersectiononceormore.ThengotoTools/DataCursor.Clickascloseasyoucanto
theintersection.Writetheresultdowntocomparewiththatobtainedbyusingthe"fzero"
commandbelow.

Nextletusconsiderapairofexplicitequations,y=sin2(x)ex/21andy=10sin(x)/x.Proceeding
asabove:
>>clearx=10:0.01:10y1=10*sin(x)./xy2=sin(x).^2.*exp(x/2)1plot(x,y1,x,y2)
Againweseethattherearemanysolutions(intersections),bothpositiveandnegative.(Note that
when MATLAB calculated sin(0)/0 it gave a warning, but nonetheless completed the other
calculationsandtheplot.)Asabove,findtheapproximatesolutionatxnear3.5.(Igetx=3.49,y
= 0.9796.) Write down your result to compare with those to be found later.Alternately, we can
equate these two equations (since both = y), move everything to the lefthand side, and find the
valuesofxwhenthisis0.Forthevalueofxfound,thecorrespondingvalueforyisdeterminedby
substitutingthisbackintoeitheroneoftheoriginalequations.
>>clearx=10:0.01:10yeq=10*sin(x)./xsin(x).^2.*exp(x/2)+1
>>yeq0=zeros(1,length(x))plot(x,yeq,x,yeq0)
Usingthesamemethodasabove,Iagaingotx=3.49andyeq=0.Notethatyeqisnoty.Tofind
theywesubstitutexbackintobothofthesimultaneousequations,whichgivesustworesults.(Use
yourownvalueofxratherthanmyvalueof3.49.)
>>clearx=3.49y1=10*sin(x)/x,y2=sin(x)^2*exp(x/2)1
Thecloserthesearey1andy2,thebetteroursolution.

Numericalsolutionofoneortwononlinearequationsinexplicitform(y=f(x))

Weusethe"fzero"command,whichfindsthevalueofxforf(x)=0.(See>>helpfzero.)Wewill
usethesameexamplesasabove.Todisplaytheresultto14significantfigureswefirstchangethe
formattolong.Forthesingleequation,sin2(x)ex/21=0:
>>clearformatlongx=fzero('sin(x)^2*exp(x/2)1',1)
(Noticethatnodotisrequirednowbefore^or*,althoughusingthedotcausesnoproblem.)How
doesthisresultcomparetotheapproximateresultyouobtainedbythegraphicalmethodabove?

Nowweagainconsiderthepairofequations,y=sin2(x)ex/21andy=10sin(x)/x:
>>clearx=fzero('10*sin(x)/xsin(x)^2*exp(x/2)+1',3.5)
>>y1=10*sin(x)/x,y2=sin(x)^2*exp(x/2)1
Asbefore,weseethatthenumericalmethodismoreaccurate.Sowhybotherwiththegraphical
methodatall?Thereasonis,toseeaboutwhereyouneedtohave"fzero"seekasolution!

http://people.clarkson.edu/~wwilcox/ES100/eqsolve.htm

2/5

12/20/2015

SolutionofEquationsusingMATLAB

Findingaparticularsolutionwhenthereareinfinitelymany

Thereareequationswithaninfinitenumberofsolutions,forexamplesin(x)=1/2.
Itishelpfultoseesomeofthesesolutionsbyplottingy=sin(x)1/2andthenobservingwherey
hasvaluesofzero:

>>clear,symsxeq='ysin(x)+1/2'ezplot(eq,[6,6,2,1])
>>holdoneq0='0'ezplot(eq0)holdoff

The "hold on" command tells MATLAB to write the subsequent plots on top of the first one,
ratherthanreplacingit.Plotting0putsahorizontallineonthegraph.Intersections of the sine
wavewiththislinerepresentsolutionsofthefirstequation.Approximatevaluescanbeobtainedin
theFigurewindowbyclickingonTools/ZoomIn,clickingonadesiredintersectiontoenlargethat
areaofthegraph,clickingonTools/DataCursor,andthenclickingonthatintersectionagainto
givetheapproximatevaluesofxandythere.Trythisonthefirsttwointersectionstotherightof
theorigin(x>0).Writedownyourresultstocomparewiththosefoundbelow.

Herearethestepstofindasolutionnumerically:

1. Converttheequationtoafunctionconsistingofeverythingmovedtothelefthandside, e.g.
func2(x)=sin(x)1/2.
2. CreatethisfunctionintheMATLABeditor,savetotheCurrentDirectory,andmakecertain
thecurrentdirectoryisinthepath(File/SetPath).Forexample:

functionout=func2(x)
out=sin(x)1/2
end

3. Plotthisfunctionovertherangeofinteresttoseewherethesolutionsare,e.g.:

>>clear,x=4:0.01:4plot(x,func2(x))

4. Useoneofthefollowingformatstofindthesolution:

>>fzero('func2',3)or>>fzero(@func2,3)or>>fzero('func2',[2,3])

MATLABfindsthevalueofxnearest3thatgivesfunc2=0.Notice(whosorWorkspace)that
theresultisdouble,sonoconversionsarenecessaryforsubsequentnumericcalculations.

Numerical solution of two or more equations in implicit forms (e.g., f1(x,y)=0,


f2(x,y)=0)

Weusethe"fminsearch"command.Considerasanexamplethefollowingtwoimplicitequations
(alreadyinMATLABformat):
0.5=(200+3*x+4*y)^2/((20+2*x+3*y)^2*x)
10=(20+2*x+3*y)*y/x
Usethefollowingsteps:
1. Moveeverythingtothelefthandsideinallequations.
2. UsingMATLAB'seditwindow,createafunctionthatcalculatesthedeviationsfrom0when
http://people.clarkson.edu/~wwilcox/ES100/eqsolve.htm

3/5

12/20/2015

SolutionofEquationsusingMATLAB

arbitraryvaluesareusedforthevariables.Thefinaloutputofthefunctionisthesumofthe
squaresofthesedeviations.Followingisthecodeforourexample,andwouldbesavedas
meth_reac.minMATLAB'sCurrentDirectory,whichmustalsobeinthePath(File/Set
Path).
functionout=meth_reac(guesses)
%functiontocalculatethevaluesofxandy
%satisfyingthetwoequibiliubriumrelations
%foramethanolreactor,CO+2H2=CH30H
%CO2+3H2=CH3OH+H2O(coaltochemscasestudy)
%xisthemolarflowrateofCO,yofCO2(kmol/h)
%Aftersaving:>>fminsearch('meth_reac',[25,3])x=ans(1),y=ans(2)
%Anypositivevaluesworkasinitialguessesinthisexample
x=guesses(1)y=guesses(2)
eq1=0.5(200+3*x+4*y)^2/(20+2*x+3*y)^2/x
eq2=10(20+2*x+3*y)*y/x
out=eq1^2+eq2^2
end

3.IntheCommandwindow,type"fminsearch('functionname',[guessedvalues]).Forour
example,
>>fminsearch('meth_reac',[25,3])x=ans(1),y=ans(2)

Youcancheckyourresultbyusingthesymbolic"solve"command,asfollowsforourexample:
>>clear,symsxy
>>eq1='0.5=(200+3*x+4*y)^2/(20+2*x+3*y)^2/x'
>>eq2='10=(20+2*x+3*y)*y/x'
>>[xy]=solve(eq1,eq2,x,y)
Notethatseveralsolutionsareproduced,fromwhichyouhavetoselectthephysicallyreasonable
one.Ifthisisthefirstsolution,thentoobtaindoubleprecisionnumericalvariablesweuse:
>>x=double(x(1)),y=double(y(1))

(Theequationsinthisexamplearebasedontheequilibriumrelationshipsforachemicalreactormaking
methanolfromCO,CO2andH2aspartofanexistingplantthatproducesavarietychemicalsstartingwiththe
gasificationofcoal,i.e.coalreactingwithwaterathightemperature.)

Numericalsolutionofsimultaneouslinearequationsusingthematrixbackslash(\)
method

MATLABusesGaussianeliminationtosolvesystemsoflinearequationsviathebackslashmatrix
command(\).Asanexample,considerthefollowingthreeequations:
2x3y+4z=5
y+4z+x=10
2z+3x+4y=0
Theprocedureisasfollows:
1. Eachequationmustfirsthaveeachvariableinthesameorderonthelefthandside,withthe
constantsontherighthandside.Thisshouldbedoneusingpencilandpaper.Studentscommonly
assumetheycandothiswhileenteringtheinformationinMATLAB,andfrequentlymakemistakes
doingso.Forourexample,wewrite:

2x3y+4z=5
x+y+4z=10
3x+4y2z=0
2. InMATLAB,creatematricesofcoefficientsforthevariablesandconstantsontherighthand
http://people.clarkson.edu/~wwilcox/ES100/eqsolve.htm

4/5

12/20/2015

SolutionofEquationsusingMATLAB

sides.Thusforourexample:

>>clear,C=[2,3,41,1,43,4,2],B=[5100]
3. Solveforx,yandzusing:
>>A=C\B,x=A(1),y=A(2),z=A(3)
Checkyourresultsusing:>>C*AB
(NotethatthesearematrixoperationsyouMUSTNOTuseadot(.)before*or\)
ComparethisresultwiththatobtainedusingMATLABsymbolicmathematicsforthesame
systemofequations.

Anotherapplicationofthebackslashmatrixoperatoristofitdatatoanonlinearequation.We
useanexamplewiththefollowingyversusdata:
>>cleart=[0,.3,.8,1.1,1.6,2.3]'y=[0.5,0.82,1.14,1.25,1.35,1.40]'plot(t,y,'o')
Noticethatthisdoesnotgiveastraightlineplot.Insteadwewilltryaquadraticfit(withoutusing
theBasicFittingtoolonthegraphwindoworthe"polyfit"command).Thatis,wewanttofindthe
valuesofthecoefficients(a0,a1,a2)thatbestfitthesedatatotheformy=a0+a1t+a2t2.Wehave
6valueseachoftandy,fromwhichwegenerate6equationsintheformata0+ta1+t2a2=y
matchingthatrequiredforsolutionofsimultaneouslinearequations:
a0=0.5
a0+0.3a1+0.32a2=0.82
a0+0.8a1+0.82a2=1.14
a0+1.1a1+1.12a2=1.25
a0+1.6a1+1.62a2=1.35
a0+2.3a1+2.32a2=1.40
Thuswehavesixsimultaneousequations,butonly3unknowns.Wecannotexpecttogetvaluesfor
a0,a1anda2thatwouldexactlysatisfyall6equations.Thebackslashoperatorgivestheleast
squaresvaluesinstead.Wemustputthese6equationsintheformC*A=B,asfollows(assumingt
andyhavealreadybeenentered,asabove):
>>C(:,1)=ones(length(t),1)
>>C(:,2)=t
>>C(:,3)=t.^2
>>B=y
>>A=C\B
>>a0=A(1),a1=A(2),a2=A(3)
>>tfit=0:0.1:2.3yfit=a0+a1*tfit+a2*tfit.^2
>>plot(t,y,'o',tfit,yfit)
Thisisageneralmethodandnotconfinedtofittingdatatopolynomials.Seefittingdatatonon
polynomialequations.

http://people.clarkson.edu/~wwilcox/ES100/eqsolve.htm

5/5

Anda mungkin juga menyukai