TransWikia.com

NMinimize sum of several fitted results

Mathematica Asked by Ricardo May on June 19, 2021

I have 10 data sets and assume them a same parameter, offset in the CorrelationFit function. I would like to minimize the residuals of the 10 fitted results with the same offset, and the minimization parameter is of course the offset.

CorrelationFit[counts_List, offset_ : 0, plot_ : True] := 
  Module[{[Phi], [Sigma], [Delta], func, 
    nlm, [Sigma]0, [Theta]},
   func = [Sigma] Sin[[Theta] + [Phi]]^2 + offset;
   [Sigma]0 = Last@Last@MaximalBy[counts, Last];
   nlm = NonlinearModelFit[
     counts, {func, 
      0 <= [Sigma] <= 1 && 0 <= [Theta] <= 2 [Pi]}, {{[Theta], 
       0}, {[Sigma], [Sigma]0}}, [Phi], Method -> "NMinimize"];
   If[plot, 
    Print[Show[
      ListLinePlot[counts, PlotRange -> All, PlotStyle -> Red], 
      Plot[nlm[[Phi]], {[Phi], 0, 
        First@First@MaximalBy[counts, First]}, PlotRange -> All, 
       PlotStyle -> Blue]]]];
   Off[FittedModel::constr];
   {Around[#[[1]], #[[2]]] & /@ ({{[Theta], [Sigma]} /. 
         nlm["BestFitParameters"], 
        nlm["ParameterErrors"]}[Transpose]), 
    Total[(Norm@nlm["FitResiduals"])^2], nlm["RSquared"]}
   (*nlm*)
   ];

The bellowing is what I have tried

NMinimize[{Total@
   Table[CorrelationFit[data[i], x, False][[2]], {i, 1, 
     Length@files}], -0.1 <= x <= 0.1}, x]

But it always outputs some errors, how can I solve the problem?

NonlinearModelFit::nrnum: The function value 1/2 ((-0.129567+x)^2+(-0.12562+x)^2+(-0.09362+x)^2+(-0.0551761+x)^2+(-0.0311761+x)^2+(-0.0309837+x)^2+(-0.021861+x)^2+(0.017861 +x)^2+(0.0191761 +x)^2+(0.0695666 +x)^2+<<3>>) is not a real number at {[Theta]$201516,[Sigma]$201516} = {0.1,0.484}.

In addition, I have tested another simpler fitting and it works

f[l_, x_Real : 1] := 
 Module[{c}, 
  c /. NonlinearModelFit[
     Table[{i, x*Sin[i/(10 [Pi])] + RandomReal[{-0.1, 0.1}]}, {i, 1, 
       100}], x*Sin[a] + c, {c}, a, Method -> "NMinimize"][
    "BestFitParameters"]]

Their fitting functions are similar, but why is the previous one with actual data not working.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP