0
$\begingroup$

The following code defines fitting models (Chebyshev and Fourier cosine functions) from a data stored in a txt file.

Clear["Global`*"] (*fitting model*)
data = Import["file.txt", "Table"];

model[m_, x_] := Sum[a[n] ChebyshevT[n, x^2/2 - 1], {n, 0, m}];
model5[m_, x_] := Sum[a[n]*Cos[n*x], {n, 0, m}];

nlm[m_Integer?Positive, x_] := 
  NonlinearModelFit[data, model[m, x], Array[a, m + 1, 0], x];
nlm5[m_Integer?Positive, x_] := 
  NonlinearModelFit[data, model5[m, x], Array[a, m + 1, 0], x];
m = 2;
Module[{model = nlm[m, x], model5 = nlm5[m, x]}, 
 Column[{Plot[
    Evaluate@{model // Normal, model5 // Normal}, {x, -2, 2}, 
    PlotRange -> Full, ImageSize -> {500, 500}, 
    Epilog -> {Red, AbsolutePointSize[4], Point[data]},
    AxesLabel -> {Style["x", 16], Style["y", 16]},PlotLegends -> 
 Placed[{Style["Cheb", 20], Style["Cos", 20]}, {1.01, .7}]]}]]

With this code I obtain the following graphic:

enter image description here

I would like to draw the plots of differences between data and both models.

$\endgroup$
1
  • 3
    $\begingroup$ Store the results of nlm and nlm5 in say fit and fit5, respectively, and then look at the residuals: fit["FitResiduals"] and fit5["Residuals"]. $\endgroup$
    – JimB
    Jun 4 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.