Derive unitary matrix for Tofolli gate I know that for two qubits, the CNOT matrix is given by
$CNOT=P_0 \otimes I + P_1 \otimes X.$
But I cannot figure out how to get the matrix if I have two control qubits, acting on a third, like in the circuit below.

How can I derive this matrix? Thank you!
 A: This gate is the so-called Toffoli gate. Its matrix representation is given by the following matrix:
\begin{bmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
\end{bmatrix}
. It's easy to see why, since the gate has to map $|110\rangle$ to $|111\rangle$, $|111\rangle$ to $|110\rangle$, and it has to leave the other elements of the computational basis unchanged.
I don't know whether it helps, but one can also write that matrix as
$$
M_0 \otimes I_4 + M_1 \otimes I_2 + M_2 \otimes X
$$
, where $M_0$ is 
\begin{bmatrix}
1 & 0 \\
0 & 0 \\
\end{bmatrix}
, $M_1$ is
\begin{bmatrix}
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 \\
\end{bmatrix}
, and $M_2$ is 
\begin{bmatrix}
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 \\
\end{bmatrix} .
A: Here is a trick in Quirk (the tool you used to make your screenshot) that will show you the matrix for any operation or combination of operations. This trick is based on the channel-state duality.


*

*Prepare a number of EPR pairs equal to the number of qubits in your circuit. Put one half of each EPR pair in a group at the top, and the others go on the bottom in the same order. You can do this with a bunch of H+CNOT gates, or slightly more quickly with a single QFT+ADD block.

*Apply the gates from your original circuit to the bottom half of this larger circuit.

*Look at the output amplitude display. It's the circuit's unitary matrix! (Actually it's only proportional to the matrix, but that's just as good.)
Here is the matrix for your circuit in Quirk, via this trick:

And the matrix for your circuit is in fact
$$\begin{bmatrix}
&&&1 \\
&&1\\
&1\\
&&&&1\\
&&&&&&&1\\
&&&&&&1\\
&&&&&1\\
1
\end{bmatrix}$$
(Note: the result depends on your convention for ordering the computational basis states w.r.t. the qubits. I am assuming the top qubit is the least significant w.r.t. the ordering.)
If you play around with the circuit in Quirk while showing the matrix, it becomes very obvious very fast how to construct the matrices.
