# How to convert a simple matrix into circuit? [duplicate]

Suppose you have an invertible matrix. How do you convert it into a circuit?

Matrices have dimensions $$2^n \times 2^n$$, so a circuit representation is desirable.

For example, the matrix below is a simple classical circuit — which is why it has no imaginary entries — but I'm not sure if it could be converted into a quantum circuit with ease.

    [ 1 0 0 0 0 0 0 0 ]
[ 0 0 0 0 0 0 1 0 ]
[ 0 0 1 0 0 0 0 0 ]
M = [ 0 1 0 0 0 0 0 0 ]
[ 0 0 0 1 0 0 0 0 ]
[ 0 0 0 0 1 0 0 0 ]
[ 0 0 0 0 0 1 0 0 ]
[ 0 0 0 0 0 0 0 1 ]

• Hi and welcome to QCSE! Your matrix is a permutation, and is reversible, so indeed there is a quantum circuit for it Do you know how to make a Boolean circuit out of your matrix, using things like AND gates and OR gates? You can change this to another circuit using CNOT gates and CCNOT gates. You’d have 3 inputs and 3 outputs ($n=3$). Do you see why? Commented May 25, 2023 at 22:11

## 1 Answer

In qiskit, you can run the following code:

    from qiskit import QuantumCircuit
from qiskit.extensions import UnitaryGate

matrix=[[ 1 0 0 0 0 0 0 0 ],
[ 0 0 0 0 0 0 1 0 ],
[ 0 0 1 0 0 0 0 0 ],
[ 0 1 0 0 0 0 0 0 ],
[ 0 0 0 1 0 0 0 0 ],
[ 0 0 0 0 1 0 0 0 ],
[ 0 0 0 0 0 1 0 0 ],
[ 0 0 0 0 0 0 0 1 ]]
gate=UnitaryGate(matrix)


and then append the gate to a quantum circuit. Please refer to this for more information.

You could also convert any unitary matrix into a linear combination of other unitary matrices (such as the H gate or X gate) and run that instead. Hope that helps!