# What is the formula for the matrix representation of a general controlled gate?

Suppose I have $$n$$-qubit circuit. I have a single-qubit gate (e.g. a Pauli gate) at qubit $$a$$ and it is controlled by the qubit $$b$$. What is the matrix representation for this controlled gate? The wires $$a$$ and $$b$$ don't have to be adjacent so I don't think I can just throw in the Kronecker product with identity. How it would generalize if the base gate is a multi-qubit gate (e.g. controlled-SWAP) or when it's controlled by multiple qubits (e.g. How do I get a Toffoli gate representation for arbitrary $$n$$)?

The general way to construct a controlled unitary operator $$U$$ with the help of projectors is as follows. The projectors $$P_{|0,1\rangle}$$ are at the index of the controlling qubit, $$U$$ is at the index of the controlled qubit: \begin{align} \label{eq:controlled} C\hspace{-.08em}U_{0{,\kern-1pt}1} = P_{|0\rangle} \otimes I + P_{|1\rangle} \otimes U. \end{align} Where the projectors are just the outer product of the basis states $$P_{|0\rangle}=|0\rangle\langle 0|$$ and $$P_{|1\rangle}=|1\rangle\langle 1|$$.
If there are $$n$$ qubits between the controlling and controlled qubits, $$n$$ identity matrices must also be tensored between them. If the index of the controlling qubit is larger than the index of the controlled qubit, the tensor products from above must be inverted. Here is an example with qubit 2 controlling gate $$U$$ on qubit 0 (bigendian, where qubit 0 is "the first" qubit): \begin{align*} C\hspace{-.08em}U_{2, 0} = I \otimes I \otimes P_{|0\rangle} + U \otimes I \otimes P_{|1\rangle}. \end{align*} This works with any size operator, not just $$2 \times 2$$ matrices, for example, to control a swap gate. You just have to make sure that there are enough identify matrices inserted to make the matrix sizes match.