11

Suppose I have a quadratic form of

qf = a x^2 + b y^2 + c z^2 + 2 d x y + 2 e x z + 2 f y z

How can I easily to get the symmetric matrix A, such that $X^TAX=qf$? where $X^T=(x,y,z)$.

I hope that the method will work for general quadratic form (i.e., for 2nd-homogenous polynomial of variable x,y,z,w,...)

I have tried the function CoefficientRules, but it seem there needs a step to transform the order of each term into the "position" of matrix.

van abel
  • 1,235
  • 1
  • 11
  • 27

3 Answers3

22

Here is a very short solution:

qf = a x^2 + b y^2 + c z^2 + 2 d x y + 2 e x z + 2 f y z;

1/2 D[qf, {{x, y, z}, 2}]
(* ==> {{a, d, e}, {d, b, f}, {e, f, c}} *)

This is just an application of the answer to Quick Hessian matrix and gradient calculation.

Jens
  • 97,245
  • 7
  • 213
  • 499
14

I think you need CoefficientArrays:

mat = Last@CoefficientArrays[qf, {x, y, z}, "Symmetric"->True];
{x, y, z}.mat.{x, y, z} == qf // Simplify
(* True *)
xzczd
  • 65,995
  • 9
  • 163
  • 468
8

Here is a way that yields symmetric matrix (for this example you could just write it down):

m=Module[{r = {x -> 1, y -> 2, z -> 3}, tu = Tuples[{x, y, z}, 2]},
 Normal@SparseArray[(## /. r) -> 
      Coefficient[qf, Times @@ ##]/(2 - Boole[#[[1]] === #[[2]]]) & /@
     tu, {3, 3}]]

yields:

{{a, d, e}, {d, b, f}, {e, f, c}}

Check:

Expand[{x, y, z}.m.{x, y, z}]

yields qf

CoefficientArrays as per @xzczd yields:

{{a, 2 d, 2 e}, {0, b, 2 f}, {0, 0, c}}

which is also a valid representation.

ubpdqn
  • 60,617
  • 3
  • 59
  • 148