# SWAP gate on 2 qbits in 3 entangled qbit system

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

Because it's entangled I can't decompose it into individual states, and because the qbits 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 qbits in an n qbit 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|$$