1
$\begingroup$

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?

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

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}}

Original answer

You can use CoefficientArrays:

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

Normal @ CoefficientArrays[ρ, {Subscript[x, 1], Subscript[x, 2]}][[3]] //TeXForm

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

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ While this is very close to what I want, is there a way to do something about the B+C? (Note that the order of x1 and x2 matter) While this is easily solvable for a 2x2 matrix, it becomes really hard to deal with for big matrices (I have to deal with 50x50 matrixes, and maybe more) $\endgroup$ – Alex May 13 '19 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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