# 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:

import numpy as np
from qiskit import QuantumCircuit

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:

$$U = \begin{bmatrix} 0 & 1 & 0 & 0 \\ 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix}$$

• 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. Aug 17, 2022 at 13:32
• @noobier I had a problem with scientific notation when using qiskit once, the solution was to use the linear algebra tools from numpy in order to use the normalization tool. In this case perhaps you could normalize your rows? (The how to use the normalization is in the answer to a question of mine here though the context was different.) Oct 13, 2022 at 11:39
• @PGibbon my problem is not normalizing, but how to bound the error introduced by the convertion of a general unitary matrix to a gate. In particular, if my matrix is just a permutation, I would like to build an exact circuit representation of the matrix. Oct 15, 2022 at 10:19
• @noobier I will not be likely to help you with this, but do you mean that when your U gate is transpiled to be run you wish the transpilation to be the same each time so that you can write a more efficient error correcting code? Oct 15, 2022 at 11:25