If I may, I wanna share an algorithmic generalization for the inspired @Danylo Y answer. This considers also The Algorithmic Method in this answer here related to the CNOT gate.
In order to algorithmically build a 2-qubit SWAP gate to operate swap within n-qubits, one could define an array containing n ID gates, i.e. ID=((1,0),(0,1))
matrices, named here as M
, and overwrite both elements, the one subscripted as qba_idx
with |i><j|
, and the one as qbb_idx
with |j><i|
, considering $i,j \in {0,1}$.
As a reference, |0><0| = ((1,0),(0,0))
, |0><1|=((0,1),(0,0))
, |1><0|=((0,0),(1,0))
, |1><1|=((0,0),(0,1))
.
So, to build the n-qubit SWAP gate, one can perform operations as:
// 'state' is the current (2^n)×1 column statevector for n-qubits
M = [ID] * n // list with n matrices of ((1,0),(0,1))
final_state = zeros((2^n, 1)) // column vector with all zeros, (2^n)×1
for i in [0,1]:
for j in [0,1]:
M[qba_idx] = ket_bra(i,j) //|i><j|
M[qbb_idx] = ket_bra(j,i) //|j><i|
swap_gate = M[0]
for m in M[1:end]:
swap_gate = kron_product(swap_gate, m)
final_state = final_state + matrix_multiply(swap_gate, state)
// final_state now has the resulting statevector with
// both qubits (qba_idx and qbb_idx) swapped
Don't forget that n-qubits will require a swap_gate
matrix with size $2^n\times2^n$. For example, 10 qubits will require a $1024\times1024$ = 1,048,576 elements. If they are of double
precision, this means 67108864 bits, or 8 Mb of memory. In the other hand 20 qubits will require something around 8 Tb of memory for swap_gate
variable only. If we consider each element as a complex number, these memory requirement just doubles. Mind that when coding your gates.