# 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|$$