Stats

341,568

Popular Posts

Followers

Mathematica 教學 constructing a piecewise function from Interpolation

戴忠淵 於 2011年5月29日星期日 上午10:16 發表


(* 輸入資料 *)

data={{8,14},{10,14},{12,17},{14,16},{16,17},{18,19},{20,13},{22,14},{24,15}};

(* 散佈圖*)

ListPlot[data,PlotStyle->{Red,PointSize[0.015]}]


(* 以不同階數建立Interpolation *)

Manipulate[
Plot[Interpolation[data,InterpolationOrder->n][x],{x,8,24},
Epilog->{Red,PointSize[0.015],Point@data},
PlotRange->{{8,24},{10,20}}],
{n,0,5,1}]




(*建立piecewise函數*)

myfun[datatemp_List,ordertemp_Integer]:=

Block[{data=datatemp,test,testans,fun,order=ordertemp,x,var,fit},

(*建立估計函數所需變數*)

var=ToExpression[CharacterRange["a","z"][[1;;order+1]]];

(*建立估計函數*)

fun[x_]=var.(x^#&@Range[order,0,-1]);

(*分割資料*)

test=Partition[data,order+1,1];

(*求解估計函數參數*)

testans=Solve[fun@test[[#,All,1]]==test[[#,All,2]],var][[1]]&/@Range[Length@test];

(*建立估計函數*)

fit=Piecewise[{fun[x]/.testans[[#]],

test[[#,1,1] ] <= x< test[[#,order,1]]}&/@Range[Length@testans]]

]    



myfun[data,3]




(* 比較2階 piecewise與內建Interpolation函數 *)

With[{n=2},
Show[
Plot[Interpolation[data,InterpolationOrder->n][x],{x,8,24},
PlotStyle->Thickness[0.02],
Epilog->{Red,PointSize[0.015],Point@data}],
Plot[Evaluate@myfun[data,n],{x,8,24},
PlotStyle->{Thickness[0.01],Green}]]
]


(* 比較3階 piecewise與內建Interpolation函數 *)

With[{n=3},
Show[
Plot[Interpolation[data,InterpolationOrder->n][x],{x,8,24},
PlotStyle->Thickness[0.02],
Epilog->{Red,PointSize[0.015],Point@data}],
Plot[Evaluate@myfun[data,n],{x,8,24},
PlotStyle->{Thickness[0.01],Green}]]
]

Tags:

讀者回應 ( 0 意見 )

發佈留言

Please leave your name and tell me what you thought about this site. Comments, suggestions and views are welcomed.

如果這篇文章對你有幫助,那請留個訊息給我~