# Does anyone has some code for Mathematica or Python to convert a diagonal matrix into Dirac (bra-ket) notation?

I have the following matrix which I have to translate into Dirac's notations. $$\begin{array}{cccccccc} \frac{1}{2} \left(q_0+q_3\right){}^2 & 0 & 0 & 0 & 0 & 0 & 0 & \frac{1}{2} \left(q_0-q_3\right){}^2 \\ 0 & \frac{1}{2} \left(q_1+q_2\right) \left(q_0+q_3\right) & 0 & 0 & 0 & 0 & \frac{1}{2} \left(q_1-q_2\right) \left(q_0-q_3\right) & 0 \\ 0 & 0 & \frac{1}{2} \left(q_1+q_2\right) \left(q_0+q_3\right) & 0 & 0 & \frac{1}{2} \left(q_1-q_2\right) \left(q_0-q_3\right) & 0 & 0 \\ 0 & 0 & 0 & \frac{1}{2} \left(q_1+q_2\right){}^2 & \frac{1}{2} \left(q_1-q_2\right){}^2 & 0 & 0 & 0 \\ 0 & 0 & 0 & \frac{1}{2} \left(q_1-q_2\right){}^2 & \frac{1}{2} \left(q_1+q_2\right){}^2 & 0 & 0 & 0 \\ 0 & 0 & \frac{1}{2} \left(q_1-q_2\right) \left(q_0-q_3\right) & 0 & 0 & \frac{1}{2} \left(q_1+q_2\right) \left(q_0+q_3\right) & 0 & 0 \\ 0 & \frac{1}{2} \left(q_1-q_2\right) \left(q_0-q_3\right) & 0 & 0 & 0 & 0 & \frac{1}{2} \left(q_1+q_2\right) \left(q_0+q_3\right) & 0 \\ \frac{1}{2} \left(q_0-q_3\right){}^2 & 0 & 0 & 0 & 0 & 0 & 0 & \frac{1}{2} \left(q_0+q_3\right){}^2 \\ \end{array}$$

It is diagonal and would be very nice if someone could help me. :)

• this matrix is not diagonal though.. – glS Nov 12 '19 at 16:12

Let's define the kets,

ket0 = {{1},{0}};ket1 = {{0},{1}};


This function produces input from a string,

f[x_?StringQ] := ToExpression[StringJoin["ket",x]];


This function produces the diagonal matrix corresponding to a string "000",

matrixFunc[x_]:= KroneckerProduct@@ f/@ StringPartition[x,1] .
ConjugateTranspose[KroneckerProduct@@ f/@ StringPartition[x,1] ] ;

matrixFunc["0001"];

A = RandomReal[1,{8,8}];M (* = INPUT MATRIX*);


This function gives the coefficient corresponding to the string (say) "001"

overlap[x_?StringQ]:= Tr[matrixFunc[x] .A];


All possible permutations in lexical (dictionary) order for comparison,

allkets = StringJoin/@ Tuples[{"0","1"},3]

• Thank you so much!! – Shivang Srivastava Nov 12 '19 at 16:14

I wrote a small package for these kinds of operations, QM, that is available on GitHub here.

Here is a couple of examples (the code above will import directly the main file from GitHub without installing it, this is enough here but some other things will require that you install the full package):

Get["https://raw.githubusercontent.com/lucainnocenti/QM/master/QM.m"];

QState@"00" + QState@"11"

QState@{1, 1}

QState[Flatten@{1, 1, 1, 1}, {{0, 1}, {0, 1}}]

QStateToDensityMatrix[QState@"00" + QState@"11"] // MatrixForm

RandomReal[{0, 1}, 2] // QState // Echo // QStateToDensityMatrix // Echo[#, "", MatrixForm] & // QDensityMatrixToKet


In particular, QDensityMatrixToKet will do what you want (although of course, the output will be reliable only when the input matrix is Hermitian).