2

How to create a quantum gate from a unitary matrix in Qiskit with code

Interested in learning how to program quantum computers? Then check out our Qiskit textbook Introduction to Quantum Computing with Qiskit.

Introduction

In this tutorial we will see how to construct a quantum logic gate from a unitary matrix.

In quantum computing unitary matrices are very important as they describe how quantum logic gates and circuits affect qubit states.

In Qiskit a quantum logic gate can be created from a unitary matrix using the Unitary class:


Unitary(data)

Where:

  • data: This is the unitary matrix that will be encoded in to the logic gate

For example the Pauli X gate can be described using the following matrix:

Using the unitary class we can implement the Pauli-X gate like so:

circuit.unitary([[0,1],[1,0]],q[0])

Where [[0,1],[1,0]] is the matrix we wish to encode and q[0] is the target qubit.


Implementation

In this section we will go through the full implementation step by step. The matrix we will be implementing is the Pauli-X gate matrix.

Step 1: Import modules

from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute
from qiskit.quantum_info.operators import Operator
from qiskit import Aer

Step 2: Initialise the Backend

The next step is to intialise the backend device. Since this is only a tutorial we will use the Aer unitary simulator:

backend = Aer.get_backend('aer_simulator')

Step 3: Create the circuit

The next step is to create the circuit. This is just a one qubit circuit that creates a Pauli-X gate using the unitary class. Then the qubit is measured.

q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')

circuit = QuantumCircuit(q,c)

circuit.unitary([[0,1],[1,0]],q[0])
circuit.measure(q,c)

Step 4: Execute the circuit and obtain the results

job = execute(circuit, backend, shots=8192)

counts = job.result().get_counts()

print(counts)

Code

from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute
from qiskit.quantum_info.operators import Operator
from qiskit import Aer

backend = Aer.get_backend('aer_simulator')

q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')

circuit = QuantumCircuit(q,c)

circuit.unitary([[0,1],[1,0]],q[0])
circuit.measure(q,c)

print(circuit)

job = execute(circuit, backend, shots=8192)

counts = job.result().get_counts()

print(counts)

Output

Output showing the qubit has flipped from |0〉to |1〉