Nonlinear model fit not fitting with good parameters. I can find the coefficients manually and origin manages to fit anyway

You need to use a constraint for c to avoid complex numbers.

fit = NonlinearModelFit[
  datatofit, {intensity[t, a, c, i, j, k], 
   c^2 < 1}, {{a, 3600}, {c, .45}, {i, -.3}, {j, 1}, {k, .4}}, t]

Show[ListPlot[datatofit], Plot[fit[t], {t, 0, 180}]]

enter image description here

Btw, as a matter of style, I would define all parameters as variables. That way you won't run into troubles if you assign a value to any of these parameters at some point.


There are some "identifiability" issues with fitting your model parameters with the data that you have. First, your data set is symmetric in that the first half of the data is identical to the second half so if any standard errors are to be believed, just half of the data needs to be used.

@Felix has given you the approach for getting NonlinearModelFit to converge. However, when looking at nlm["CorrelationMatrix"] one sees very large correlations (with some being suspiciously close to 1.0).

$$\left( \begin{array}{ccccc} 1. & -0.752256 & -0.103413 & 0.99936 & -0.927615 \\ -0.752256 & 1. & -0.441861 & -0.730288 & 0.695337 \\ -0.103413 & -0.441861 & 1. & -0.135651 & -0.0770068 \\ 0.99936 & -0.730288 & -0.135651 & 1. & -0.926308 \\ -0.927615 & 0.695337 & -0.0770068 & -0.926308 & 1. \\ \end{array} \right)$$

This is strongly suggestive that the model is overparameterized. Consider expanding and collecting terms in the function being fitted:

FullSimplify[Expand[intensity[t]]]

$$\frac{1}{256} a \left(3 \cos (2 t) \left(c^2 (-64 i+39 j+32)+64 \sqrt{1-c^2} c (k+2)+64 i\right)+2 c \left(8 \sqrt{1-c^2} (11 k+8)+c (-32 i+29 j-84)\right)+9 c \left(2 \cos (4 t) \left(8 \sqrt{1-c^2} k+3 c j+4 c\right)+3 c j \cos (6 t)\right)+64 (i+4)\right)$$

This is of the form

$$\text{a0}+\text{a1} \cos(2t)+\text{a2} \cos(4t)+\text{a3} \cos(6t)$$

We see that there are just 4 parameters needed to characterize the function rather than 5. We can now perform a fit on half of the data:

nlm = NonlinearModelFit[datatofit[[Range[1, 90], All]], a0 + a1 Cos[2 t] + a2 Cos[4 t] + a3 Cos[6 t], {a0, a1, a2, a3}, t];
nlm["BestFitParameters"]
(* {a0 -> 4094.8464407396978, a1 -> 2737.6662380018993, a2 -> 724.3603397546482, a3 -> 154.1540954251538} *)
nlm["CorrelationMatrix"] // MatrixForm 

$$\left( \begin{array}{cccc} 1. & -0.0157271 & 0.000698895 & -0.0157271 \\ -0.0157271 & 1. & -0.0222359 & 0.00074129 \\ 0.000698895 & -0.0222359 & 1. & -0.0222359 \\ -0.0157271 & 0.00074129 & -0.0222359 & 1. \\ \end{array} \right)$$

That correlation matrix looks close to ideal.