Skip to main content

symbolic - Extract variable and coefficient from equation elegantly


I have quadratic equation like $eq = x2-7*x5^2$ and vector $xx=\{x0,x1,x2,x3,x4,x5,x6,x7,...\}$. I need to do some nice calculations which will give me coefficient $k=7$, $y=x2$ and $x=x5$, so that equation $y=k*x^2$ is the same as my original equation. Eq is a good equation, so finding $k$, $y$ and $x$ is possbile. How can I do this?



Answer




I'm not sure what exactly you want to achieve, but let it be for a start.


eq = x2-7 x5^5

One can extract the list of variables by


xx = Variables[eq]


{x2, x5}



Then, find the list of exponents and coefficients:



rules = CoefficientRules[eq, xx]


{{1, 0} -> 1, {0, 2} -> -7}



The output means that the first coordinate, x2, has power 1 (that comes from the {1,0} part) and a coefficient 1; the second coordinate, x5, has power 2 and coefficient -7. (You can add a term like x2 x5 to see how it works.)


That gives a list of rules that one can use to reproduce the initial polynomial eq with arbitrary variables:


eqNew = FromCoefficientRules[rules, {y, x}]



-7 x^2 + y



I understand that your eq==0, so


Simplify[eqNew == 0]


7 x^2 == y



Or


y = y /. First@Solve[eqNew == 0, y]



7 x^2



assigns 7 x^2 to y:


y


7 x^2




but I don't know how general you want it to be and what purposes should it serve.


Comments