# Get slope of linear fit

This may seem silly, but I've been crazy for the last hour trying to find a way to automate the linear fit of my data. All I need is the slope.

Say I have some data list={1,2,3,4,5,6,7,8}; and want to find the slope that fits it best, something like m = Slope[list], so that I can use m wherever I want.

Fit[{1, 2, 3, 4, 5, 6, 7}, {1, x}, x] returns me 4.0284*10^-15 + 1. x, in wich case the value I want is 1.. How can I get that value programmaticly? The function Fit returns the results in a not very useful form... Why?

Notice that I have 2337 curves to fit. I can't do them all by eye or copy and paste. Surely I'm missing something.

Thanks

• D[Fit[{1, 2, 3, 4, 5, 6, 7}, {1, x}, x], x]? Commented Jun 28, 2016 at 15:35
• Coefficient[Fit[{1, 2, 3, 4, 5, 6, 7}, {1, x}, x], x] works too. Commented Jun 28, 2016 at 15:42
• Or if you want a sophisticated way, lm = LinearModelFit[{1, 2, 3, 4, 5, 6, 7}, {1, x}, x]; First@Pick[lm["BestFitParameters"], lm["BasisFunctions"], x]. There are lots of fitting functions. Try ?*Fit. Commented Jun 28, 2016 at 15:43
• @J.M. Better than D, esp. when the model has other functions. Commented Jun 28, 2016 at 15:44
• if you've given your LinearModelFit a variable name like lm then Coefficient[ lm[x], x ] will work.
– Joe
Commented Feb 5, 2018 at 6:21

Putting my comment into a function:

bestFitSlope[data_] := Module[{lm, x},
lm = LinearModelFit[data, {1, x}, x];
First@Pick[lm["BestFitParameters"], lm["BasisFunctions"], x]
];

Example. Suppose you have a list of datasets, then you can Map (/@) the function bestFitSlope over the list.

SeedRandom[0, Method -> "MersenneTwister"];
n = 6;                        (* number of datasets to make uo *)
slopes = RandomReal[5, n];    (* slopes of the lines *)
datasets = Table[
20 i + slopes[[i]] x + RandomReal[{-2, 2}], (* line + noise *)
{i, n}, {x, 15}];

ListPlot@datasets

The we can get the slopes of the fitted lines and compare them with the "theoretical" slopes:

bestFitSlope /@ datasets
slopes
(*
{2.12046, 2.90695, 0.189475, 3.72127, 0.314697, 4.21059}
{2.1471, 2.90036, 0.151295, 3.81398, 0.253895, 4.23242}
*)

Note: The function bestFitSlope throws away the linear model it constructs. You might want to keep it for the other information it contains (see LinearModelFit).

• Yes. The solution does seem to be to define the Slope[list_]:=... function. I just wasn't used to manipulating data if not in lists or value output. Commented Jun 29, 2016 at 21:06

Here's a simple way.

lineData = Fit[list, {1, x}, x];
val  = Last[lineData];
val /. x -> 1

This will give you the value of the slope of the linear fit.

• Note, that this only works, if the result is always returned exactly in the form a + b x, and never as b x + a (or only b x, etc.). Commented Dec 6, 2023 at 10:56
list = {1, 2, 3, 4, 5, 6, 7, 8};