I would like to ask about the results of running the Toffoli gate matrix and circuit diagram on colab

enter image description here

Possible reasons for inconsistent results with the following correct matrix results.enter image description here

I would also like to ask if there is any way to obtain the correct matrix result through qiskit?

  • 1
    $\begingroup$ it's probably just that qiskit counts qubit bottom up. The matrix you wrote amounts to an X applied to the first qubit conditionally to second and third being 1 $\endgroup$
    – glS
    Commented May 22 at 11:25
  • $\begingroup$ See this video for details: youtu.be/WcYC7fEXcFE?si=r_WRlEsbVtjBBaMl $\endgroup$
    – diemilio
    Commented May 22 at 17:42

1 Answer 1


This is because Qiskit uses tensor ordering convention different from what is used in most quantum computing textbooks. According to a recent preprint from Qiskit team:

When interpreting circuits, a convention must be picked for the ordering of qubits in a register, arguments of all instructions, and of instructions themselves. For example it is common that instructions in a circuit are ordered from left to right (i.e. temporal ordering), which is the opposite of how gate matrices are multiplied in the circuit.

Throughout Qiskit, tensor products are ordered as $Q_2 \otimes Q_1 \otimes Q_0$. For example, the Pauli $ZX$ means Z1X0. In this convention, the computational basis can be conveniently represented as $|000⟩=|0⟩, |001⟩=|1⟩, |010⟩=|2⟩, |011⟩=|3⟩$, etc.

This leads to more natural representations of reversible circuits too,as numbers are encoded in qubit registers in the same way as they would be in classical registers. Note that this is merely a convention, which may be natural for some tasks but not others. For example, the qubit arguments to a $CX$ instruction are ordered as $Q_0$=control and $Q_1$=target, This leads to a unitary of $CX= \left( {\begin{array}{*{20}{c}} 1&0&0&0 \\ 0&0&0&1 \\ 0&0&1&0 \\ 0&1&0&0 \end{array}} \right)$ , which may be different to some textbook definitions of the gate.

QuantumCircuit class contains the method reverse_bits() which can be used to reverse the order of wires. Similarly, Operator class contains reverse_qargs() method. You can use any one of them to get the expected matrix:

op = Operator(qc.reverse_bits())


op = Operator(qc)
  • $\begingroup$ Thank you very much💕your answer is very helpful $\endgroup$
    – Dona
    Commented May 23 at 9:59

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.