Quick Mathematica squib

I have spent a lot of time manipulating multivariate polynomials in Mathematica, and have been very frustrated at trying to make Coefficient behave the way I think it should. I think Coefficient[2x+3xy, x] should be 2, Mathematica thinks it should be 2+3y. Or rather, I don’t think that this should be the default, but it is very often my desired behavior and I can’t find an option to tell Mathematica that’s what I want.

I just wrote a little snippet to do this for me, and I’m copying it here so I can reuse it in the future:

myCoeff[poly_, vars_, exp_] :=
     If[Max[exp] == 0, poly, Coefficient[poly, Apply[Times, vars^exp]]] /.
       Map[(# -> 0) &, vars]

For example, myCoeff[2 x + 3 x*y, {x, y}, {1, 0}] is 2, just as I want. Note that myCoeff[2k*x+2x*y, {x,y}, {1,0}] is 2k; so you can still easily have Mathematica treat some variables as constants.

UPDATE Code simplified a bit, because I realized that creating useless replacement rules wouldn’t do any harm.


4 thoughts on “Quick Mathematica squib

  1. It’s always frustrating if Mathematica behaves a bit different than expected. But couldn’t you use CoefficientList in this case?

  2. Not really. I imagine you are thinking something like

    (* I did not test this code *)

    L = CoefficientList[poly, vars];

    indexer=Sequence[Map[{#}&, exp+Table[1, {i,1,Length[expr]}]];

    (* This messy formula describes where inside CoefficientList the term we want is, using the formula that Take[] wants for input. *)

    First[Take[L, indexer]]

    But this only works if exp is in the range of monomials which Mathematica uses to create CoefficientList. For example, myCoeff[x+2, {x}, {100}] won’t work with the above implementation. You could add a test for that; I don’t know if that would be better in some way.

  3. Hi Scott! As it happens, I just started looking at mathematica.SE a few days ago; I’ve left 1 question and 2 answers so far. I tend to feel embarrassed to ask for ways to do basic things like this though.

Comments are closed.