How do I extract the matrix from an density matrix equation?

I have a density matrix equation and I wish to put it in the form of a matrix.

For example, if I have:

$$\rho =Ax_{1}x_{1}+Bx_{1}x_{2}+Cx_{2}x_{1}+Dx_{2}x_{2}$$

Copy-and-paste version

ρ =
A Subscript[x, 1]^2 + B Subscript[x, 1] ** Subscript[x, 2] +
C Subscript[x, 2] ** Subscript[x, 1] + D Subscript[x, 2]^2

I want the result to be:

$$\begin{bmatrix}A&B\\C&D\end{bmatrix}$$

Is there a simple way to do it for an n by n matrix?

• If you really want non-commutative multiply, you have written the expression for $rho$ incorrectly. May 13 '19 at 16:02
• You are right, I just edited it to (what I think) is the good expression.
– Alex
May 13 '19 at 16:54

Update

It was not clear from your original question that you were using noncommutative variables. In that case, the input needs to indicate this. In particular, x^2 is used for commutative multiplication, so it would be better to use x**x instead. So:

ρ = a Subscript[x, 1]**Subscript[x, 1] + b Subscript[x, 1]**Subscript[x, 2] + c Subscript[x, 2]**Subscript[x, 1] + d Subscript[x, 2]**Subscript[x, 2];

Then, you can use Coefficient:

Map[
Coefficient[ρ, #]&,
Outer[NonCommutativeMultiply, {Subscript[x, 1],Subscript[x, 2]}, {Subscript[x, 1], Subscript[x, 2]}]
]

{{a, b}, {c, d}}

$$\left( \begin{array}{cc} A & B+C \\ 0 & D \\ \end{array} \right)$$