Page 1 of 1

How do you build a gate from a matrix on Qiskit?

Posted: Tue Jul 18, 2023 10:50 am
by quantumadmin
In Qiskit, you can build a gate from a matrix by using the UnitaryGate class. Here's a step-by-step guide on how to do it:

Import the required modules:

Code: Select all

from qiskit import QuantumCircuit
from qiskit.extensions import UnitaryGate
Define the matrix representation of the gate you want to build. For example, let's say you have a 2-qubit gate with the following matrix:

Code: Select all

matrix =         [[1, 0, 0, 0],
                       [0, 0, 1, 0],
                       [0, 1, 0, 0],
                       [0, 0, 0, 1]]
Create a UnitaryGate object from the matrix:

Code: Select all

qc = QuantumCircuit(2)
qc.append(gate, [0, 1])  # Applying the gate to qubits 0 and 1
That's it! You have successfully built a gate from a matrix and applied it to a quantum circuit in Qiskit. You can continue to work with the circuit, apply additional gates, and execute it on a quantum device or simulator.

Note: The matrix you provide should be unitary and compatible with the number of qubits in your circuit.