I have multiple sets of data, and I want to apply Linear Model Fit sequentially to each set of data. For example, below tstlst contains 3 data sets. Right now I have created a function which will take in the super set, and then apply LinearModelFit to each one of the three.

My question is, how do I extend this to work for any number of sub sets? For example, if tstlst were to contain 100 subsets of data then my current approach would be impossible. I want to be able to generalize the function to work for any number of sets.

tstlst = { { {1, 2}, {2, 3}, {4, 5} },

{ {10, 11}, {12, 13}, {14, 15}},

{ {100, 200}, {300, 400}, {500, 600}}}

linearModelFitSet[dataset_] :=

{LinearModelFit[dataset[[1, 1 ;; 3,All]],x, x],

LinearModelFit[dataset[[2, 1 ;; 3, All]], x, x],

LinearModelFit[dataset[[3, 1 ;; 3, All]], x, x]}

linearModelFitSet[tstlst]

gives:

{FittedModel[1. +1. x],FittedModel[1. +1. x],FittedModel[100. +1. x]}

=================

Use the tool almost every list-processing procedure in Mathematica uses: Map (shorthand /@), and familiarize yourself with functions of the # & kind. LinearModelFit[#, x, x] & /@ tstlst

– kirma

Jul 7 ’15 at 17:53

=================

1 Answer

1

=================

You need to create a pure Function and Map it over the first level of tstlst like so:

LinearModelFit[#, x, x] & /@ tstlst

Now tstlst can have as many sets as you like without you having to know how many in advance.