I defined and evaluated a function

Max2[t_?NumericQ] := Log[Abs[-1 + First[Maximize[sol1[[2]][x, t], 0 <= x <= L, x]]]];

Now, I expect this to be close to a straight line as a function of $t$, so I would like to get the best slope from a fit.

Looking at the reference website, I don't understand how to linearly fit a function.

  • 2
    $\begingroup$ You have provided incomplete information. How come on earth we will know what sol1[[2]][x, t] or the value of x are? Without this info no one can address the problem here. $\endgroup$ Nov 17, 2013 at 15:11
  • $\begingroup$ One way to find a linear fit to a function is by taking the derivative. $\endgroup$
    – bill s
    Nov 17, 2013 at 15:19

1 Answer 1


Let's take a vaguely straight function like you say yours is:

Plot[Log[t], {t, 50, 100}]


You could fit a line to it by sampling a bunch of points:

data = Table[{t, Log[t]}, {t, 50, 100}];

And fitting a line through those:

fit = Fit[data, {1, t}, t]
(*  3.2732 + 0.0136576 t  *)

Or you could minimise the integral of the square difference (i.e. least squares) directly yourself:

fit2 = a + b t /. Last@NMinimize[Integrate[(a + b t - Log[t])^2, {t, 50, 100}], {a, b}]
(*  3.27497 + 0.0136447 t  *)

They both give similar results:

Plot[{Log[t], fit, fit2}, {t, 50, 100}]


  • $\begingroup$ Thanks a lot! How can I extract the slope from the output fit, without making the derivative? $\endgroup$ Nov 17, 2013 at 23:41
  • $\begingroup$ You could use a rule fit /. m_ t + c_ :> m or pick out the right part fit[[2, 1]] $\endgroup$
    – wxffles
    Nov 18, 2013 at 1:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.