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?


1 Answer 1


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

  • $\begingroup$ 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. $\endgroup$
    – consthatza
    Aug 17, 2022 at 13:32
  • $\begingroup$ @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.) $\endgroup$
    – PGibbon
    Oct 13, 2022 at 11:39
  • $\begingroup$ @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. $\endgroup$
    – consthatza
    Oct 15, 2022 at 10:19
  • $\begingroup$ @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? $\endgroup$
    – PGibbon
    Oct 15, 2022 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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