1
$\begingroup$

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]}
$\endgroup$
  • $\begingroup$ 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 $\endgroup$ – kirma Jul 7 '15 at 17:53
4
$\begingroup$

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.

$\endgroup$

Your Answer

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

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