# Qiskit: Is there an efficient way to convert custom operator (matrix) to circuits/gates and vice versa?

I'm using qiskit and would like to convert easily between matrix operators and their corresponding circuits. I have 2 types of operators:

1. Permutation matrices (binary entries only) which must be converted without error to a circuit
2. General unitary matrices for which I can tolerate a small error

The matrices are in numpy format.

How can this be achieved? And how much of an error is introduced?

You can use the unitary() method of the QuantumCircuit object in the following way:

U = np.array([[0,1,0,0], [1,0,0,0], [0,0,0,1], [0,0,1,0]])
qc = QuantumCircuit(2)
qc.unitary(U, qubits = qc.qubits, label = "U")


Here I applied the following simple permutation matrix as an operator acting upon a system of 2 qubits:

And the resulted circuit is:

Since the matrix shown above is just the matrix operator of applying a $$NOT$$ gate on $$q0$$ and do nothing to $$q1$$, if we transpile the resulted circuit we get the result we expected:

tpQC = transpile(qc, basis_gates = ['id', 'rz', 'sx', 'x', 'cx', 'reset'])
display(tpQC.decompose().draw())


For further information you can also look at:

1. This concise video.
2. This GitHub documentation.
• Is there a way to ensure that this operation is exact when dealing with permutations? I wouldn't like for example the corresponding matrix to have values like 1e-9 but exactly zero. yesterday