Getting LinearModelFit to report fit at each value in a list.

The documentation for LinearModelFit

shows how to evaluate the model at a single point.

I

n[1]:= data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}};

In[2]:= lm = LinearModelFit[data, x, x]

In[6]:= lm[2.3]

Out[6]= 1.78475

Picking another point, in this case 3.1

In[4]:= lm[3.1]

Out[4]= 2.34068

But

In[5]:= lm[{2.3, 3.1}]

does not give me the list of values {1.78475, 2.34068} as I want.

Any ideas?

Either

Map[lm, {2.3, 3.1}]

or equivalently

lm /@ {2.3, 3.1}

Edit: Bill beat me to it! (:

Hello David!

I believe that being able to supply a list and get the function threaded over the list only applies to functions with the attribute Listable. You can get the same affect by manually adding the Thread function, or mapping the list over the function using Map or the /@ operator:

lm /@ {2.3, 3.1}

Thread[lm[{2.3, 3.1}]]

Hope that helps

Thank you both. Those solutions were a lot more elegant than mine, which involved trying to create a table to get out individual elements. I thought there must be a simpler way, but just was unsure how.

Dave

SetAttribute can give you the automatic threading feature:

In[6]:= f[x_]:=lm[x]
In[7]:= SetAttributes[f,Listable]
In[10]:= f[{2.3,3.1}]
Out[10]= {1.78475,2.34068}

Hi Shenghui Yang,
Is there any advantage in a function not being Listable? I can’t see why the default it not to be listable. I assume there must be some reason that’s not the default behavior.

Hi David!

It is not always obvious which arguments should be threaded and which should not. Using the Thread function you can specify how arguments are to be threaded. However, with the Listable attribute, the default behavior of Thread seems to be used (thread over all lists). For example:

SetAttributes[f, Listable]
Thread[f[{1, 2, 3}, {a, b, c}]]

Out[1]: {f[1, a], f[2, b], f[3, c]}

It is easy to think of a scenario where that behavior is not what you want.

Even if you could specify which arguments are to be threaded, sometimes you want to supply a list and not have it threaded at all. The Plot function illustrates this nicely:

Thread[Unevaluated[Plot[{x, x^2}, {x, 0, 1}]], List, 1]

This gives two Plots in a list. The default behavior for Plot, i.e. not Listable, would plot the two functions in the first list together, in the same graph which is most likely what you are looking to do.

That being said, according to the documentation:

Most built-in mathematical functions are Listable. »

Hope that helps!

Thank you everyone. I’m satisfied with the solution now.

Dave