# How do I write the matrix for a CZ gate operating on nonadjacent qubits?

I'm working on a teleport protocol and I need to open the matrix of each operator, however, there's a CZ gate between q0 and q2 at the end of it and I don't know how to write the matrix for it and operate in the state.

This is the protocol, really basic, and the CZ is the last one.

Consider that a control qubit is $$q_k$$ and a target qubit is $$q_{k+n}$$ and you want to apply operator $$U$$ on the target qubit. Denote $$N=2^{n+1}$$. Then matrix representation of this controlled $$U$$ is $$$$CU= \begin{pmatrix} I_{\frac{N}{2}} & O_{\frac{N}{2}} \\ O_{\frac{N}{2}} & I_{\frac{N}{4}} \otimes U \\ \end{pmatrix}$$$$

In your case $$U=Z=\begin{pmatrix}1 & 0 \\ 0 & -1\end{pmatrix}$$, $$k=0$$ and $$n=2$$, so the matrix representation of operator $$Z$$ acting on $$q_{2}$$ controlled by $$q_{0}$$ is

$$$$\begin{pmatrix} 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 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ \end{pmatrix}$$$$

You can write the controlled-phase gate, as applied to just those two qubits, as $$I\otimes I-2|1\rangle\langle 1|\otimes |1\rangle\langle 1|.$$ If you want these to act on qubits 1 and 3, then you need to apply identity, $$I$$, on the second qubit: $$I\otimes I\otimes I-2|1\rangle\langle 1|\otimes I\otimes |1\rangle\langle 1|.$$

What you need is:

1. SWAP q[1] and q[2]
2. Do CZ on q[0] and q[1] (note that we have q[2] in it right now)
3. SWAP q[1] and q[2]

In terms of matrices, all you need is to multiply 3 8x8 matrices.

Hope it will help.