I’m trying to curve fit an arbitrary sum of distributed gaussians to a function — each with their own set of parameters. Currently, if I want to use twenty functions, I do the following
φ[α_?NumberQ, x_?NumberQ, xi_?NumberQ, c_?NumberQ] := (
c E^(- α (x - xi)^2/2))/Sqrt[α/π];
Data := Table[{n/50, N[f[n/50]]}, {n, -300, 300}];
model = φ[a1, x, x1, c1] + φ[a2, x, x2, c2] + φ[a3, x, x3, c3] +
φ[a4, x, x4, c4] + φ[a5, x, x5, c5] + φ[a6, x, x6, c6] +
φ[a7, x, x7, c7] + φ[a8, x, x8, c8] + φ[a9, x, x9, c9] +
φ[a10, x, x10, c10] + φ[a11, x, x11, c11] + φ[a12, x, x12, c12] +
φ[a13, x, x13, c13] + φ[a14, x, x14, c14] + φ[a15, x, x15, c15] +
φ[a16, x, x16, c16] + φ[a17, x, x17, c17] + φ[a18, x, x18, c18] +
φ[a19, x, x19, c19] + φ[a20, x, x20, c20];
nlm = NonlinearModelFit[Data,
model, {a1, x1, c1, a2, x2, c2, a3, x3, c3, a4, x4, c4, a5, x5, c5, a6, x6,
c6, a7, x7, c7, a8, x8, c8, a9, x9, c9, a10, x10, c10, a11, x11, c11,
a12, x12, c12, a13, x13, c13, a14, x14, c14, a15, x15, c15, a16, x16, c16,
a17, x17, c17, a18, x18, c18, a19, x19, c19, a20, x20, c20}, x];
This works well but it is tedious to create these linear combinations by hand. It would be wonderful to create a linear combination of functions with a vector of coefficients for a, xi, and c. I am just unsure of how to approach this and I was hoping that you guys could offer some insight into this.
Best,
Thomas
I did something just like this before:
Just replace n with however many Gaussians you need. Obviously if you have different basis functions you’ll have to do other things, but this works nicely when you’re working just a set of (or even two) basis functions.
Here’s some proof of concept code: