Re: Piecewise function generator
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg1155] Re: Piecewise function generator
- From: pasquale Nardone <pnardon at ulb.ac.be>
- Date: Sat, 20 May 1995 01:03:20 -0400
- Organization: Universite' Libre de Bruxelles
You can define a function that compute the coefficient a and b in the linear expression a*x+b and the segment where this hold fff[{pt1_,pt2_}]:={ LessEqual[pt1[[1]],x,pt2[[1]]], Apply[Divide,Reverse[pt2-pt1]]*x-Det[{pt1,pt2}]/Apply[Plus,(pt2-pt1)*{1,0}] }; then you can use recursive tricks fff[{pt1_,pt2_,restOfpts__}]:=Join[fff[{pt1,pt2}],fff[{pt2,restOfpts}]]; and it will work pts={{20,0.08},{50,0.8},{250,0.8},{5000,0.004}}; g[x_]=Apply[Which,fff[pts]]; nb: of course fff could be define more easily using explicit representation: hhh[{{x1_,y1_},{x2_,y2_}}]:={ LessEqual[x1,x,x2], ((y2-y1)*x+y1*x2-y2*x1)/(x2-x1)}; hhh[{pt1_,pt2_,restOfpts__}]:=Join[hhh[{pt1,pt2}],hhh[{pt2,restOfpts}]] g[x_]=Apply[Which,hhh[pts]] Out[] Which[20 <= x <= 50, (-12. + 0.72*x)/30, 50 <= x <= 250, (160. + 0.*x)/200, 250 <= x <= 5000, (3999. - 0.796*x)/4750] and if you want to have the possibility to define your variable name : qqq[{{x1_, y1_}, {x2_, y2_}}, var_] := {x1 <= x <= x2, ((y2 - y1)*var + y1*x2 - y2*x1)/(x2 - x1)}; qqq[{pt1_, pt2_, restOfpts__}, var_] := Join[qqq[{pt1, pt2}, var], qqq[{pt2, restOfpts}, var]]; gnew[t_]:=Apply[Which,qqq[pts,t]] gnew[X] Out[] Which[20 <= x <= 50, (-12. + 0.72*X)/30, 50 <= x <= 250, (160. + 0.*X)/200, 250 <= x <= 5000, (3999. - 0.796*X)/4750] I hope this could help P. Nardone