# How can I extract a matrix and vectors of coefficients from this quadratic expression?

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?

• Look at the documentation for CoefficientList. Commented Apr 27 at 15:36

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