MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Import polynomial from file and define function

  • To: mathgroup at
  • Subject: [mg112147] Re: Import polynomial from file and define function
  • From: Patrick Scheibe <pscheibe at>
  • Date: Thu, 2 Sep 2010 02:31:00 -0400 (EDT)


maybe it helps when you have a function which does all that stuff for
you by taking either a filename or a polynomial as string and the
symbols you want to assign:

SetAttributes[makePolynomial, HoldRest]; 
makePolynomial::invpar = "An error occured parsing the input \
  string or in creating the polynomial."; 
makePolynomial[polyOrFilename_String, f_Symbol, 
     vars__Symbol] := Block[{polystr, expr}, 
     If[FileExistsQ[polyOrFilename], polystr = 
          Import[polyOrFilename, "Text"], 
        polystr = polyOrFilename]; If[SyntaxQ[polystr], 
        expr = ToExpression[polystr]; 
         If[PolynomialQ[expr, {vars}], 
           Evaluate[f @@ (Pattern[#1, _] & ) /@ {vars}] := 
             Evaluate[expr], Message[makePolynomial::invpar]; 

Now you can do something like

makePolynomial["x^5 + 5*x^4*y + 10*x^3*y^2 + 10*x^2*y^3 + 5*x*y^4 +
y^5", f, x, y]


or even 

makePolynomial["~/tmp/polynomial.txt", g, x, y]

Hope this helps.


On Wed, 2010-09-01 at 06:27 -0400, nick_twisp wrote:
> Hello Mathematica community,
> I am looking for a solution of the following problem:
> I have some quite long polynomial in q and x stored in a file and
> with
> test = Import["this_file_containing_the_polynomial"];
> I import the string and with
> poly = ToExpression[test];
> I convert it to an expression. If I usually would like to define a
> function (like in this case in x and q) from it, I would write
> F[q_, x_] := poly;
> Unfortunately this doesn't work at all. Strange enough if I just paste
> the huge expression behind F[q_, x_]:=, then it works and I have a
> function in q and x, which is evaluated when I put a concrete number
> e.g. for q (then becoming a polynomial in x).
> Does someone have an idea, how I could define a function from an
> expression?
> Thanks in advance,

  • Prev by Date: Difficult constrained optimization problem
  • Next by Date: Re: 2 dimensional engineering problem
  • Previous by thread: Difficult constrained optimization problem
  • Next by thread: Difficulties with LocatorPanel