11
$\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$
13
$\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

|improve this answer|||||
$\endgroup$
  • $\begingroup$ Thanks, this works if you do x^Range[0, n - 1].coeffArr $\endgroup$ – Gest May 8 '13 at 8:09
  • $\begingroup$ @Gest Now you've got what you wanted, Plus is Listable too. $\endgroup$ – Artes May 8 '13 at 8:12
7
$\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]]
|improve this answer|||||
$\endgroup$
  • $\begingroup$ (Use Reverse[] if you have a different arrangement of the coefficients, of course.) $\endgroup$ – J. M.'s technical difficulties May 8 '13 at 7:58

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.