# SWAP gate on 2 qubits in 3 entangled qubit system

Suppose I had 3 entangled qubits and I wanted to apply a SWAP gate on the first and third qubit.

Because it's entangled I can't decompose it into individual states, and because the qubits are not adjacent I can't simply take a Kronecker product with an identity matrix.

How would I go about creating the matrix for applying this transformation? Also is there a generalization for swapping 2 arbitrary qubits in an n qubit system?

Gates don't depend on states they act on. So it doesn't matter if the state is entangled or not. The gate you've described (let's call it $$U$$) acts on a standard basis by this rules $$U |0x0\rangle = |0x0\rangle$$ $$U |0x1\rangle = |1x0\rangle$$ $$U |1x0\rangle = |0x1\rangle$$ $$U |1x1\rangle = |1x1\rangle$$ for each $$x=0$$ and $$x=1$$.

You can write this matrix as $$U=\sum_{x=0}^1 \big(|0x0\rangle\langle 0x0 |+|1x0\rangle\langle 0x1 |+|0x1\rangle\langle 1x0 |+|1x1\rangle\langle 1x1 | \big) =$$ $$= |0\rangle\langle 0| \otimes I \otimes |0\rangle\langle 0| + |1\rangle\langle 0| \otimes I \otimes |0\rangle\langle 1| + |0\rangle\langle 1| \otimes I \otimes |1\rangle\langle 0| + |1\rangle\langle 1| \otimes I \otimes |1\rangle\langle 1|$$

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.