4
$\begingroup$

I want to run LinearModelFit where the number of parameters is not fixed. For example, the following

i = 2;
data = RandomReal[20,{10,3+i}];
lm1 = LinearModelFit[data,FromLetterNumber[Range[2+i]],FromLetterNumber[Range[2+i]];

doesn't work, whereas

lm1 = LinearModelFit[data,{a,b,c,d},{a,b,c,d}]

works as per described, despite FromLetterNumber[Range[2+i]] == {a,b,c,d}

Can this be made to work using some kind of Hold or do I need to resort to a design matrix, response vector format?

$\endgroup$
5
$\begingroup$

FromLetterNumber returns a String:

Head @ FromLetterNumber @ 3

String

You can wrap the strings returned by FromLetterNumber with Symbol or ToExpression to get Symbols:

lm1 = LinearModelFit[data, Symbol /@ FromLetterNumber[Range[2+i]], 
  Symbol /@ FromLetterNumber[Range[2+i]]];
Normal @ lm1

9.60642 + 0.175108 a - 0.723711 b + 0.850788 c - 0.198777 d

Alternatively,

lm2 = LinearModelFit[data, Array[a, 2 + i], Array[a, 2 + i] ] ;
Normal @ lm2

9.60642 + 0.175108 a[1] - 0.723711 a[2] + 0.850788 a[3] - 0.198777 a[4]

$\endgroup$
  • 2
    $\begingroup$ The Array version should be the canonical choice, IMHO. +1 $\endgroup$ – Marius Ladegård Meyer Aug 6 '18 at 9:34

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.