0

I'm trying to fit some data into a model using the standard procedure of minimizing the chi-square function using this code:

ClearAll["Global`*"]
Needs["ErrorBarPlots`"];
a0 = 1;
b0 = 2;

sol[a_, b_] := NDSolve[{x'[t] == -ax[t] + Sin[t], y'[t] == ax[t] - by[t]^2, z'[t] == by[t] - Cos[t], x[0] == 1, y[0] == 0, z[0] == 0}, {x, y, z}, {t, 0, 10}, MaxSteps -> Infinity];

F[t_] := x[t] + y[t]^2 + z[t]^3;

wsol[a_, b_] := (wsol[a, b] = NDSolve[{w'[t] - w[t] - ((F[t] /. sol[a, b])[[1]]) == 0, w[0] == 0}, w, {t, 0, 10}]);

model[t_, a_, b_] := (w[t] /. wsol[a, b])[[1]] // Chop;

SeedRandom[1264645]; rangoT = Range[0, 9, 0.5]; ndat = Length[rangoT];

DATA = Table[{t, model[t, a0, b0] + RandomVariate[NormalDistribution[0, .1]], RandomReal[{.05, .1}]}, {t, rangoT}];

chi2[a_, b_] := Sum[((DATA[[i, 2]] - model[DATA[[i, 1]], a, b])/DATA[[i, 3]])^2, {i, 1, ndat}]

FindMinimum[chi2[a, b], {w, 0.9}, {b, 1.1}]

But when I run it I get error messages from the FindMinimum command related to NDSolve and ReplaceAll. Everything runs just fine until using that command. I was wondering why's not working and what should be changed.

xzczd
  • 65,995
  • 9
  • 163
  • 468
Syn1110
  • 51
  • 3
  • What error message do you get? Do you still get an answer? – MarcoB Dec 03 '23 at 02:27
  • 1
    The evaluation of DATA doesn't work. NDSolve throws copious errors at that point. Is that not the case for you? – MarcoB Dec 03 '23 at 02:33
  • @MarcoB that's my case... But everything appears when using the FindMinimum. Errors related to NDSolve and ReplaceAll... If you evaluate chi2 function, everything is ok – Syn1110 Dec 03 '23 at 03:47
  • 1
  • So something is already wrong in the line DATA=..., please correct the description. 2. Use something rather than t in the Table will fix the issue. (Don't forget t is already used in those NDSolves and you haven't localize them! ) 3. {w, 0.9} in last line is obviously wrong. 4. You need _?NumericQ, see this post for more info: https://mathematica.stackexchange.com/a/26037/1871
  • – xzczd Dec 03 '23 at 04:28