Curve Fitting With MATLAB
Curve Fitting With MATLAB
MATLABhasabuiltinfunctionforgeneratingtheleastsquaresfitlinethrougha
dataset(x,y)
Thesyntaxis:
>>[c,R2]=linefit(x,y)
Uselinefitforthedataset:
x=[1020304050607080];
y=[257038055061012208301450];
>>[c,R2]=linefit(x,y)
c=
19.4702
234.2857
R2=
0.8805
Interpretationofthisoutcomeisthatthebestfitlinehastheequationy=
19.4702x234.287,thecoefficientofcorrelationR2valueforthisfit0.8805
Nextwewillexplorehigherorderpolynomialfitsforthesamedatasetand
hopefullyimprovetheR2value
IndealingwithpolynomialfunctionswithinMATLABweshouldusuallysubmitthe
coefficientsofthepolynomialsindescendingpowersofxasfollows:
f(x)=p1xn+p2xn1++pnx+pn+1
1|P a g e
Ifthereisamissingcoefficientinsertazeroinitsplace.
e.g.rootsofapolynomial,polynomialmanipulations,etc.
Manualfittingoflinesthroughdata
Computationofthefitparametersisaccomplishedbyimplementingthefollowing
treatmentoftermsinthedata
Example
Computemandbforthisdata
xi
1
2
3
4
5
15
yi
0.6
2.0
3.5
5.2
5.8
17.1
xi^2
1
4
9
16
25
55
yi^2
.36
4.0
12.25
27.04
33.64
77.29
xiyi
.6
4.0
10.5
20.8
29.0
64.9
2|P a g e
Applytheformulatocomputem
m=5(64.9)(15*17.1)/(5*5515^2)=1.36
b=(17.11.36*15)/(5)=0.66
Thusy=1.36x0.66
SimilarlycomputetheR2valuebycarefulsubstitution
3|P a g e
PolynomialfittingwithMATLAB
Herewewillexploretwocommonfunctionsthatusuallygohandinhand,polyfit
andpolyval
PolyfitisabuiltinMATLABfunctionforfittingpolynomialthroughdatasets.The
syntaxis:
>>polyfit(x,y,n)
Wherexandyareorderedpairsofthedatasetunderconsideration,andnisthe
orderofthepolynomialtobeused.Applyingthissyntaxdatasetgivenearlier:
>>a=polyfit(x,y,1)
a=
19.4702234.2857
Noticethatthetwocoefficientsechoedbythepolyfitcommandrepresenta
linearfunction
Theresultisidenticaltotheonegeneratedwiththelinefitfunction,thatisy=
19.4702x234.287,astraightlinewithaslopeof19.4072andayinterceptof
234.2857
Nowusepolyvaltocomputethenumericalvalueofthefitpolynomialusingthe
coefficientsaofthefitpolynomialfromthepolyfitfunctionwhenxtakesa
specificvaluee.g.45
>>polyval(a,45)
ans=
641.8750
4|P a g e
Nowtryusinghigherorderpolynomialstoimprovethefitquality
Hereisascriptusedforexperimentingwithpolynomialfitofthegivendataset.
Readthecommentsingreentocomprehendtheeffectofthecommandsused
%Polyfitdemonstrattion
x=[1020304050607080];
y=[257038055061012208301450];
%Generateasixthorderpolynomialfitthroughthedata
cp=polyfit(x,y,6)
%Defineadensearrayofdatafortherangeofxvalues
xfit=linspace(min(x),max(x));
%Defineadensearrayofdatafortherangeofyvalues
%usingthecpfitpolynomialcoefficientsatcorrespondingvaluesinthearray
%forthexfitvalues
yfit=polyval(cp,xfit);
%Generateaplotofthe
plot(x,y,'r.',xfit,yfit,'b')
grid
xlabel('x'),ylabel('y')
title('sixthorderpolynomialfitthroughthedataset')
legend('rawdata','fitdata')
Seeplotnextpage
5|P a g e
6|P a g e