# Matrix representation of any conditioned gate

Is there an algorithm explaining how to represent any gate in the matrix form? Suppose, the circuit is the following:

where operator $$U = e^{iA\pi/4} = \begin{bmatrix} 0.35-0.85i & -0.35-0.15i \\ -0.35-0.15i & 0.35-0.85i \end{bmatrix}$$,

and the final CU operator has the following matrix representation:

$$\begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0.35-0.85i & 0 & 0 & 0 & -0.35-0.15i & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0.35-0.85i & 0 & 0 & 0 & -0.35-0.15i\\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & -0.35-0.15i & 0 & 0 & 0 & 0.35-0.85i & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -0.35-0.15i & 0 & 0 & 0 & 0.35-0.85i \end{bmatrix}$$

The question is how to understand that the final matrix will be like this? And if to firstly apply the H gate on the 0-th qubit, what it changes in matrix? Or to take another control qubit? In other words, I'm interested in the gate formation from the martrix point of view

The general way to construct a controlled unitary operator $$U$$ with the help of projectors is the following: $$$$\label{eq:controlled} CU_{0, 1} = P_{|0\rangle} \otimes I + P_{|1\rangle} \otimes U$$$$
with $$P_{|0\rangle} = |0\rangle\langle 0| \\ P_{|1\rangle} = |1\rangle\langle 1|$$

If there are $$n$$ qubits in between controlling and controlled qubit, $$n$$ identity matrices have to be tensored in between as well. If the index of the controlling qubit is larger than the index of the controlled qubit, the tensor products need to be inverted. Here is an example with qubit 2 controlling qubit 0: $$\begin{equation*} CU_{2, 0} = I \otimes I \otimes P_{|0\rangle} + U \otimes I \otimes P_{|1\rangle} \end{equation*}$$

• works with paper and pen! Cool, thank you! Commented Jan 31, 2023 at 19:42
• you said "in general", there are options when this solution does not work? Commented Jan 31, 2023 at 19:48
• No exceptions that I'm aware of. Commented Jan 31, 2023 at 20:01