How do I simulate this simple quantum circuit in MATLAB? I want to simulate a circuit similar to the one below in MATLAB. If you have a state matrix describing the state of 3 qubits, I understand that you could apply a CNOT matrix tensored with and identity matrix to $\psi_{0} $ get $\psi_{1}$, but if you want to apply a controlled operation to the 1st and 3rd qubit to get $\psi_2$, how can you do this? It's like you need "remove" the information about the second qubit, apply a CNOT gate, and then somehow integrate the result back with the superposition of the second qubit... I do not understand how to do this.
In general if I have a superposition of N qubits, how do I apply a controlled operation on qubits i and j?

 A: I think this will answer your question. How does the CNOT between qubits one and three work?
$$\left|000\right\rangle \to \left|000\right\rangle$$
$$\left|001\right\rangle \to \left|001\right\rangle$$
$$\left|010\right\rangle \to \left|010\right\rangle$$
$$\left|011\right\rangle \to \left|011\right\rangle$$
$$\left|100\right\rangle \to \left|101\right\rangle$$
$$\left|101\right\rangle \to \left|100\right\rangle$$
$$\left|110\right\rangle \to \left|111\right\rangle$$
$$\left|111\right\rangle \to \left|110\right\rangle$$
So its matrix would look like:
$$\left(\begin{array}{cccccccc}
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 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
\end{array}\right)$$
A: The answer is $|\psi_{FINAL}\rangle = CNOT_{12} \cdot CNOT_{13} \cdot |\psi_{INITIAL}\rangle$
;
where $|\psi_{INITIAL}\rangle = |\psi\rangle \otimes |00\rangle$.
So this operation goes as follows: 

*

*1st) if $|\psi\rangle$ is in state $|1\rangle$, then perform NOT on the 3rd qubit ($|0\rangle$ goes to $|1\rangle$ in the 3rd position).

*2nd) if $|\psi\rangle$ is in state $|1\rangle$, then perform NOT on the 2nd qubit ($|0\rangle$ goes to $|1\rangle$ in the 2nd position).

The matrix representation is:
$$
\begin{matrix}
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 & 0 & 0 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
\end{matrix}
$$
