12
$\begingroup$

I have the coefficients of my desired polynomial in an array CoefArr (I'm new to mathematica, so I think of everything as arrays, it is actually a list I believe) starting with the constant at index 1.

I want to turn this into a function I can evaluate like this:

f[x_] := CoefArr[[1]][[1]] + x*CoefArr[[2]][[1]] + etc. 

So I can just do f[5] and get the answer. Is there a way to do this in general?

$\endgroup$

5 Answers 5

16
$\begingroup$

A bit more succint syntax you can reach with Dot, first define an array :

n = 10; (*choose the length of array if not defined*) coeffArr = RandomInteger[10, n] 
{2, 3, 10, 10, 9, 4, 9, 4, 6, 10} 

and the result (since Power is Listable)

x^Range[0, n - 1].coeffArr 
 2 + 3 x + 10 x^2 + 10 x^3 + 9 x^4 + 4 x^5 + 9 x^6 + 4 x^7 + 6 x^8 + 10 x^9 

alternatively x^(Range[n] - 1).coeffArr

% // TraditionalForm 

enter image description here

$\endgroup$
2
  • $\begingroup$ Thanks, this works if you do x^Range[0, n - 1].coeffArr $\endgroup$ Commented May 8, 2013 at 8:09
  • $\begingroup$ @Gest Now you've got what you wanted, Plus is Listable too. $\endgroup$ Commented May 8, 2013 at 8:12
10
$\begingroup$

If you have an array of polynomial coefficients, you can use FromDigits[] in a most unconventional role:

coeffs = Range[10]; g[x_] = Expand[FromDigits[coeffs, x]] 10 + 9 x + 8 x^2 + 7 x^3 + 6 x^4 + 5 x^5 + 4 x^6 + 3 x^7 + 2 x^8 + x^9 

You could also use Fold[] to implement Horner's method, if you wish:

g[x_] = Expand[Fold[(#1 x + #2) &, 0, coeffs]] 
$\endgroup$
1
  • $\begingroup$ (Use Reverse[] if you have a different arrangement of the coefficients, of course.) $\endgroup$ Commented May 8, 2013 at 7:58
3
$\begingroup$

Borrowing the following from @Artes

n = 10; coeffArr = RandomInteger[10, n] 

{3, 9, 4, 8, 2, 5, 1, 5, 7, 3}

you can use the undocumented

Internal`FromCoefficientList[coeffArr, x] 

to get

3 + 9 x + 4 x^2 + 8 x^3 + 2 x^4 + 5 x^5 + x^6 + 5 x^7 + 7 x^8 + 3 x^9

$\endgroup$
2
  • 1
    $\begingroup$ (+1) Another undocumented function, very neat! :-) $\endgroup$ Commented Dec 29, 2023 at 22:47
  • 1
    $\begingroup$ @E.Chan-López thanks a lot! :-) $\endgroup$ Commented Dec 30, 2023 at 2:53
1
$\begingroup$

For reference, here's the obvious solution to generate a univariate polynomial of degree $n-1$, where your coefficients are in coeff list of length n:

Sum[coeff[[i]] x^(i-1), {i, 1, n}] 
$\endgroup$
1
$\begingroup$

Grabbing the @bmf's list and using FromCoefficientRules:

list = {3, 9, 4, 8, 2, 5, 1, 5, 7, 3}; coeffRules = Thread[List /@ Range[Length@# - 1, 0, -1] -> #] &; FromCoefficientRules[coeffRules@#, x] &@list (*3 + 7 x + 5 x^2 + x^3 + 5 x^4 + 2 x^5 + 8 x^6 + 4 x^7 + 9 x^8 + 3 x^9*) 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.