I have a code that fits a sine wave to small sections of a large data set and uses this to create an envelope function. I am trying to extract one of the fit parameters for each iteration of the For loop using Reap
and Sow
. So far I have this code:
Rawdata = Flatten[Import["2018050902.xlsx"]];
l1 = Table[l1, {l1, 0, 538}];
Data1 = MapThread[List, {l1/149.44444444, Rawdata}];
Minifit = Reap[For[(i = 1; j = 11), i < 540 && j < 540, (i += 11; j += 11),
nlm = Quiet@ NormalNonlinearModelFit[Part[Rawdata, i + 1 ;; j], (a*(Sin[b t + c]))
+ d, {{a, 1}, {b, 0.3}, {c, 8}, {d, -0.5}}, t]];
Sow[Amp = a /. "BestFitParameters"]]][[2, 1]]
l = Table[l, {l, 5.5, 533.5, 11}];
Bigfit = MapThread[List, {l/149.44444444, Minifit}];
Show[ListLinePlot[Data1, PlotRange -> All, PlotStyle -> {Purple}, Frame -> True,
FrameLabel -> {"Stage Position (ns)", "Visibility", "55.147mT, No Pulse"},
BaseStyle -> {FontFamily -> "Calisto MT", Bold, 20}],
ListLinePlot[Bigfit, PlotRange -> All, PlotStyle -> {Thick, Black}]]
envfit = Normal[NonlinearModelFit[Bigfit, s Exp[-a t] (Sin[b t + c])^2 +
f, {{s, 0.5}, {a, 1}, {b, 1.5}, {c, 8}, {f, 0}}, t]]
PeakPos = Part[l/149.44444444, Flatten[Position[Amp, Max[Part[Amp, 8 ;; 49]]]]];
Peak = Max[Amp];
Show[ListLinePlot[Bigfit, PlotRange -> All, PlotStyle -> {Thick, Red}],
ListPlot[{Flatten[{{PeakPos, Peak}}]}, PlotMarkers -> {"x", Large}, PlotStyle -> {Black}]]
Show[Plot[envfit, {t, 0, 3.6}, PlotRange -> All,
PlotStyle -> {Thick, Red, Dashed}, Frame -> True,
FrameLabel -> {"Stage Position (ns)", "Visibility", "55.147mT, No Pulse"},
BaseStyle -> {FontFamily -> "Calisto MT", Bold, 20},
PlotLegends -> {Style["20A", GrayLevel[0.35], FontFamily -> "Calisto MT", 20, Bold]}]]
but there seems to be a problem in the Sow
command. I want to find the value of the amplitude of the NonlinearModelFit
(given by the parameter a) from each iteration of the For Loop but I'm not sure how to get it as a list. The command for finding a
is correct as I can move it to outside the For
loop and get the final value of a
. Should I somehow make the output into a table of values of a
or somehow make a
into a parameter dependent on t
?
I'm also looking into how to get error bars for the fitting model mathematica is using. Is there an obvious way to do this?
Minifit = ...
withMinifit = Reap[For[(i = 1; j = 11), i < 540 && j < 540, (i += 11; j += 11), nlm = Quiet@ NonlinearModelFit[ Part[Rawdata, i + 1 ;; j], (a*(Sin[b t + c])) + d, {{a, 1}, {b, 0.3}, {c, 8}, {d, -0.5}}, t]; Sow[a /. nlm["BestFitParameters"]]]][[2, 1]]
? $\endgroup$Minifit
without aFor
loop andReap/Sow
isMinifit2 = a /. Quiet@ NonlinearModelFit[ Part[Rawdata, # ;; # + 9], (a*(Sin[b t + c])) + d, {{a, 1}, {b, 0.3}, {c, 8}, {d, -0.5}}, t][ "BestFitParameters"] & /@ Range[2, 539, 11]
$\endgroup$