Factorising blinear forms with Mathematica

Say I have some symbolic output that looks like the following:

expr = A a1 b1 + B a1 b2 + C a2 b1 + D a2 b2


I would like to factorise this in the following way:

Input: FactorQuadratic[expr, {a1, a2}, {b1, b2}]

Output: { { A, B }, { C, D } }

In such a way that $$\begin{bmatrix} a_1 & a_2\end{bmatrix} \begin{bmatrix} A & B \\ C & D \end{bmatrix}\begin{bmatrix}b1\\b2\end{bmatrix}$$ is equal to the original expression.

Is there a function that does this, or something like it? The closest I'm aware of is FactorList, but I'm not entirely sure how to slice and dice indices on it to make it do what I want.

• Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. May 31, 2021 at 4:42

Per this answer, you can compute the Hessian:

D[A a1 b1 + B a1 b2 + C a2 b1 + D a2 b2, {{a1, a2}}, {{b1, b2}}]
(* {{A, B}, {C, D}} *)

• Accepted this one since it's shorter, and has an obvious behavior in the case that a1=b1, a2=b2. Jun 1, 2021 at 3:52

Maybe this:

expr = $$A a1 b1 +$$B a1 b2 + $$C a2 b1 +$$D a2 b2;
v1 = {a1, a2};
v2 = {b1, b2};

Last@CoefficientArrays[#, v2] & /@
Last@CoefficientArrays[expr, v1] // Normal

(*  {{$$A,$$B}, {$$C,$$D}}  *)


Note C and D are protected symbols and not meant to be used as user parameters.