4
$\begingroup$

Consider the following expression

(x-y+a)^2 + (x-z+b)^2 // Expand

The result is

a^2 + b^2 + 2 a x + 2 b x + 2 x^2 - 2 a y - 2 x y + y^2 - 2 b z - 2 x z + z^2

Now I want to write code that extracts the coefficients into a matrix and a vector so that I can rewrite the original expression as {x,y,z}.M.{x,y,z} + v.{x,y,z}+ w, where M is a matrix and v is a vector and w is a number.

I tried Coefficient, but then when I use it for example with variable x it also gives me things that depend on y and z which is not what I want.

How can I do this?

$\endgroup$
1
  • 2
    $\begingroup$ Look at the documentation for CoefficientList. $\endgroup$ Commented Apr 27 at 15:36

1 Answer 1

4
$\begingroup$

The function you are looking for is "CoefficientArrays". E.g. for your polynomial:

var = {x, y, z};
poly = (x - y + a)^2 + (x - z + b)^2;

we get the number, vector and matrix you are looking for by:

{num, vec, mat} = CoefficientArrays[poly, {x, y, z}]

With this we may write the original polynomial as:

poly1=num + vec . var + var . mat . var 

a^2 + b^2 + (2 a + 2 b) x + 2 x^2 - 2 a y + y (-2 x + y) - 2 b z + 
 z (-2 x + z)

To test if this is correct:

poly == poly1 // Simplify

True
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.