| Author |
Comment/Response |
uwe
|
03/30/10 4:25pm
Hi!
I'm trying to define a general one-dimensional piecewise linear function to use it inside FindFit.
The problem is that I do not manage it to generally define the function f. Precisely I do not want to list as many functions g as k has elements minus 1. How can I automate this step?
Any ideas?
Thanks!
Here is my code:
############################################
k = {0, 5, 10, 15}
data = Table[{x, x^2}, {x, 15}]
g[n_, a_, b_] :=
a[[n]]*x + (b[[1]] +
Sum[k[[i + 1]]*(a[[i]] - a[[i + 1]]), {i, n - 1}])
f[a1_, a2_, a3_, b1_] :=
Piecewise[{{g[1, {a1, a2, a3}, {b1}],
k[[1]] <= x <= k[[2]]}, {g[2, {a1, a2, a3}, {b1}],
k[[2]] < x <= k[[3]]}, {g[3, {a1, a2, a3}, {b1}],
k[[3]] < x <= k[[4]]}}]
{a1, a2, a3, b1} = {a1, a2, a3, b1} /.
FindFit[data, f[a1, a2, a3, b1], {a1, a2, a3, b1}, x]
Show[Plot[f[a1, a2, a3, b1], {x, 0, 15}], ListPlot[data]]
#############################################
URL: , |
|