# How to generate matrix for swap(a, b) gate for n qubits

I am trying to simulate a swap gate that swaps two qubits of indices a and b where there are n qubits total. I understand how to make a truth table and generate a matrix based off of that for each individual case but I'm having trouble implementing a general way to do this for an arbitrary total number of qubits. Any help is appreciated.

• Welcome to QCSE. Are you wishing to perform a controlled SWAP, that is controlled off of the particular indices $a$ and $b$? Perhaps this question may be of some help. Feb 10, 2022 at 21:19
• by "implementing" do you mean to find a gate decomposition for it?
– glS
Feb 10, 2022 at 22:19
• If you just had two qubits, do you already know how to perform swap between those two? Feb 11, 2022 at 7:15
• When there are irrelevant qubits, you can perform multiple SWAP gates to make the target (or control) qubits adjacent to each other, this won't be of tremendous effort for numerical computation Feb 22, 2022 at 2:41

I am assuming you are trying to figure out a matrix that represents this type of circuit: In such case, first realize the decomposition of SWAP gate: Therefore, if you know how to implement the circuit below then you will pretty much done. To implement the circuit above, recall the definition of $$CNOT_{1,2}$$ (The first qubit is the controlled and the second qubit is the target):

$$CNOT_{1,2} = |0\rangle \langle 0| \otimes I + |1 \rangle \langle 1| \otimes X$$

But here we wanted to implement $$CNOT_{2,4}$$ instead since the second qubit is the controlled and the fourth qubit is the target. In such case, you can write it as

$$CNOT_{2,4} = I \otimes |0\rangle \langle 0| \otimes I \otimes I + I \otimes |1 \rangle \langle 1| \otimes I \otimes X$$

Also note that by definition:

$$CNOT_{2,1} = I \otimes |0\rangle \langle 0 | + X \otimes |1\rangle \langle 1 |$$

I think you can finish it off now.