Re: Re: NonlinearFit works not so good

*To*: mathgroup at smc.vnet.net*Subject*: [mg49633] Re: [mg49587] Re: NonlinearFit works not so good*From*: DrBob <drbob at bigfoot.com>*Date*: Sun, 25 Jul 2004 02:55:37 -0400 (EDT)*References*: <cdqqa4$kkd$1@smc.vnet.net> <200407240747.DAA05792@smc.vnet.net>*Reply-to*: drbob at bigfoot.com*Sender*: owner-wri-mathgroup at wolfram.com

Omega Consulting's "Copy as InputForm" palette is very useful for making readable posts: http://eclecticdreams.net/DrBob/copy_as_inputform.htm The code in Kevin's post is the same as this: p1 = Plot[100 Sin[3 x + 1] + 2, {x, 0, 5}]; data = p1[[1, 1, 1, 1]]; p2 = ListPlot[data]; f[a_, b_, c_, d_, x_] := a Sin[b x + c] + d lsfit[a_, b_, c_, d_] := Plus @@ Apply[ (f[a, b, c, d, #1] - #2)^2 &, data, {1}] lsfit[100, 3, 0, 2] sol = FindMinimum[lsfit[a, b, c, d], {a, 90, 91}, {b, 2.5, 2.6}, {c, 0, 1}, {d, 0, 1}, MaxIterations -> 1000] Plot[f[a, b, c, d, x] /. sol[[2]], {x, 0, 5}, Epilog -> {AbsolutePointSize[ 4], p2[[1]]}]; The exponent 2 in the definition of 'lsfit' caused all that unreadable junk! Bobby On Sat, 24 Jul 2004 03:47:17 -0400 (EDT), Kevin J. McCann <kmccann at umbc.edu> wrote: > I am a simple kinda guy; so, I tend to use a "roll-your-own" LSQ whenever > possible. I do this especially when I have a multivariate fit. The real > problem is that it is that there is no single answer due to the periodicity > of the sine. This makes a numerical search complicated. Anyway, here is my > version. > > \!\(\* > RowBox[{\(p1 = Plot[100\ Sin[3\ x + 1] + 2, {x, 0, 5}];\), > "\n", \(data = p1[\([\)\(1, 1, 1, 1\)\(]\)];\), > "\n", \(p2 = ListPlot[data];\), "\n", > RowBox[{\(f[a_, b_, c_, d_, x_]\), ":=", > StyleBox[\(a\ Sin[b\ \ x + c] + d\), > FormatType->StandardForm]}], > "\n", \(lsfit[a_, b_, c_, d_]\ := \ > Plus\ @@ Apply[\ \((f[a, b, c, d, #1] - #2)\)\^2 &, data, {1}]\), > "\n", \(lsfit[100, 3, 0, 2]\), > "\n", \(sol = > FindMinimum[ > lsfit[a, b, c, d], {a, 90, 91}, {b, 2.5, 2.6}, {c, 0, 1}, {d, 0, 1}, > MaxIterations \[Rule] 1000]\), > "\n", \(Plot[f[a, b, c, d, x] /. sol[\([\)\(2\)\(]\)], {x, 0, 5}, > Epilog \[Rule] {AbsolutePointSize[4], p2[\([\)\(1\)\(]\)]}];\)}]\) > > Cheers, > Kevin -- DrBob at bigfoot.com www.eclecticdreams.net

**References**:**Re: NonlinearFit works not so good***From:*"Kevin J. McCann" <kmccann@umbc.edu>