# Extracting coefficients from g=a*x+b*y+c*x*y

I have a Response Surface Equation (RSE) that I'm trying to extract coefficients from. It has a form similar to:

g = a*x + b*y + c*x*y;


I want to be able to extract the coefficient from x, y, and x*y.

However, when I use

Coefficient[g, x, 1]


I get (a + c y), which is not what I want (I want just a). Is there any way to extract a, b, and c directly?

-
It sounds like you want to find Coefficient[g,x,1] and Coefficient[g,y,0] which you could do (in this particular case) with Coefficient[g, x, 1] /. y -> 0 – bobthechemist Dec 19 '13 at 14:29
Coefficient[g /. y->0, x, 1] – Ymareth Dec 19 '13 at 14:31
Also, {1, 0} /. CoefficientRules[g, {x, y}] which is probably a bit more robust. – bobthechemist Dec 19 '13 at 14:34
Hi! and welcome to Math.SE. I've formatted your code, but please take the time to learn how to format your posts. (For code, indent four spaces or back ticks. There's also a code button, {}, above the edit window.) – Michael E2 Dec 19 '13 at 14:42
@bobthechemist Why not to formulate your reply as an answer? – Alexei Boulbitch Dec 19 '13 at 14:48

It seems to me that CoefficientRules is appropriate:

g = a*x + b*y + c*x*y;

rules = CoefficientRules[g, {x, y}]

{{1, 1} -> c, {1, 0} -> a, {0, 1} -> b}


You can extract whatever you wish from that rules list, e.g.:

{1, 0} /. rules

a


And I just noticed that bobthechemist already suggested all of this, so full credit to him.

Attempting to make this answer more my own here is a function that may automate your task. Now corrected thanks to ubpdqn.

myCoefficientRules[poly_, vars_List] :=
Times @@ (vars^#) -> #2 & @@@ CoefficientRules[poly, vars] // Sort


Result:

myCoefficientRules[g, {x, y}]

{x -> a, y -> b, x y -> c}

-

A unsorted version similar to Mr. Wizard:

f[exp_, var_] :=
CoefficientRules[exp, var] /.
Rule[List[a__], y_] :> Inner[Power, var, List[a], Times] -> y


Example:

f[a x^2 + b x z + c x y z , {x, y, z}]


yields: {x^2 -> a, x y z -> c, x z -> b}

-
Forehead slap. Why did I use Pick instead of Power?! I must steal this as my answer is broken without it. Big +1! – Mr.Wizard Dec 20 '13 at 8:29
@Mr.Wizard very kind, thank you – ubpdqn Dec 20 '13 at 8:39

In fact bobthechemist has already given a good answer. However, just to give another view on it. This:

g = a*x + b*y + c*x*y + d*x^2*y + e*x^2*y^3;
lst = List @@ g

(*  {a x, b y, c x y, d x^2 y, e x^2 y^3}  *)


transforms the polynomial into a list. This:

    Select[lst,
MemberQ[#, y] && Not[MemberQ[#, x]] && Not[MemberQ[#, x^n_]] &]

(*   {b y}   *)


selects the term only with y. This

% /. y -> 1 // First

(*  b  *)


Returns the coefficient.

-