The CNOT gate is a 2-qubit gate. This means that it acts on a 2-qubit vector, which is 4-dimensional. Thus, this gate can be represented as a 4-by-4 matrix. The gotcha is that on a pair of qubits, there can be two CNOT gates. The difference is which qubit is used as control.
By definition, the controlled-NOT gate leaves the state unchanged if the control qubit is not set, otherwise it applies a NOT gate to the target qubit. The familiar case is the first qubit as control:
This leads to the following matrix representation:
What is the matrix representation of the other CNOT gate, where the second qubit is control? Well, I was quick and wrote:
but this is wrong! If you explicitly write down how it acts on basis vectors, you can see why:
In this case, the matrix representation is:
Lesson: do not be so quick!
The two CNOT gates are related:
Here, \(H\) is the Hadamard gate:
You can check this with Python:
import numpy as np
CNOT12 = np.matrix([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
], dtype=float)
CNOT21 = np.matrix([
[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0],
], dtype=float)
H = np.matrix([
[1, 1],
[1, -1],
], dtype=float) / np.sqrt(2)
HH = np.kron(H, H)
print(np.allclose(CNOT21, HH @ CNOT12 @ HH))
The \(\operatorname{CNOT}_{21}\) gate makes an appearance in the following situation: consider constructing a 2-qubit gate \(G\) that when acting on the four Bell states, returns one of the information basis vectors as follows:
Since \(G\) is taking an ortho-normal basis to another ortho-normal basis, you can write \(G\) as:
The matrix representation of \(G\) is given by
This matrix can also be written as
I leave it as a homework problem to write it in terms of \(\operatorname{CNOT}_{21}\).