Part II. Mathematical Core · Chapter 11
Matrices as Gates
Every gate in a quantum program is a matrix, and every matrix is a multiplication you can do by hand in under a minute. This chapter gets you multiplying — X, Z, and H against real state vectors — until gate notation becomes arithmetic instead of vocabulary.
In this chapter 8 sections
Reader question. How does matrix multiplication predict a quantum gate's action on every possible input state?
A gate matrix is a linear operator whose columns are its outputs on the ordered basis; multiplying it by a statevector combines those basis actions, making linearity, ordering, and matrix composition sufficient to predict the circuit.
- This chapter does not prove the full spectral theorem or classify all one-qubit unitaries.
- It does not encourage memorizing gate names without verifying their matrices.
Read a gate by its columns
Interpret each column as a transformed basis vector.
A one-qubit gate is a matrix, and applying it means multiplying that matrix by the state vector. One hard constraint rides along: a closed-system gate must preserve total probability, which forces the matrix to be unitary; the next chapter makes that condition precise.
The three workhorses, defined by their action:
Each line is a matrix-vector product, not a slogan. X swaps the amplitudes. Z flips the sign of the component. H reshapes each basis state into an equal superposition with a specific sign pattern; and that sign pattern is the whole point, as the worked example shows.
Evidence boundary. Linear operators are represented by matrices once an ordered basis is fixed. [John Watrous] [Michael A. Nielsen]
Multiply one state by X, Z, H, and S
Carry exact complex arithmetic through the standard set.
A candidate gate is checked with the unitarity condition:
Which guarantees the matrix preserves the norm of every input state. The Hadamard carries one more identity worth memorizing: . H is its own inverse, and because it turns computational-basis information into phase-sensitive superpositions, it opens an enormous fraction of the algorithms in this book.
Evidence boundary. A gate's columns specify its action on basis vectors and linearity extends that action to every state. [Michael A. Nielsen] [John Preskill]
Composition order is execution order reversed
Relate circuit time to matrix products.
Evidence boundary. Matrix products compose gates in an order that must be reconciled with circuit chronology. [John Watrous] [Michael A. Nielsen]
Notation contract: Column-vector convention; basis order (|0>,|1>); circuit G1 then G2 corresponds to G2G1; equality up to global phase labeled.
The HZH identity exposes phase
Derive HZH=X entry by entry.
Gate matrices are the instruction semantics of the circuit model, and they get interpreted at three distinct layers:
- Ideal matrix; what the mathematics says the operation does.
- Compiled circuit; what the transpiler emits for a specific device's native gate set and topology.
- Physical operation; what calibrated pulses actually execute, with noise.
Debugging means locating the broken layer. If the ideal matrix result is wrong, no transpiler will save the program. If the ideal result is right but the compiled circuit is too deep, you have a resource-cost problem. If both are right but hardware counts are wrong, suspect noise, calibration, or connectivity. This is also why hand calculation keeps its value in the SDK era: it is the only layer you can check with a pencil.
Three matrix checks before trust
Verify shape, norm preservation on tests, and expected basis action.
Check dimensions first: an n-qubit gate is 2^n by 2^n in the declared basis order. Check columns next: each column is the output of one basis input, so column norms and pairwise inner products expose normalization or reversibility errors. Finally apply the matrix to at least one asymmetric superposition; basis-only tests can miss wrong phases even when the truth table looks correct.
Gate matrix test bench
| Field | Reader-visible record |
|---|---|
| Format | Tested Python module with exact reference matrices and composition checks |
| Verification | Tests every basis action, H²=I, HZH=X, and agreement between sequential and composed execution. |
| Availability | Source-embedded acceptance record; no separate download is claimed |
{
"artifact": "Gate matrix test bench",
"format": "Tested Python module with exact reference matrices and composition checks",
"acceptance_test": "Tests every basis action, H²=I, HZH=X, and agreement between sequential and composed execution.",
"publication_state": "source-embedded contract and worked fixture"
}Executable reference fixture
Run with Python 3.11 or later. The final assertion is the chapter-level pass condition for this small instance.
import math
def shape(matrix):
if not matrix or not matrix[0] or any(len(row) != len(matrix[0]) for row in matrix):
raise ValueError("matrix must be nonempty and rectangular")
return len(matrix), len(matrix[0])
def matvec(matrix, vector):
rows, columns = shape(matrix)
if columns != len(vector):
raise ValueError("matrix/vector dimension mismatch")
return tuple(sum(matrix[row][column] * vector[column] for column in range(columns))
for row in range(rows))
def matmul(left, right):
left_rows, shared = shape(left)
right_rows, columns = shape(right)
if shared != right_rows:
raise ValueError("matrix product dimension mismatch")
return tuple(tuple(sum(left[row][k] * right[k][column] for k in range(shared))
for column in range(columns)) for row in range(left_rows))
def max_error(left, right):
return max(abs(a - b) for row_a, row_b in zip(left, right) for a, b in zip(row_a, row_b))
scale = math.sqrt(0.5)
I = ((1, 0), (0, 1))
X = ((0, 1), (1, 0))
Y = ((0, -1j), (1j, 0))
Z = ((1, 0), (0, -1))
H = ((scale, scale), (scale, -scale))
S = ((1, 0), (0, 1j))
gates = (X, Y, Z, H, S)
identities = (matmul(H, H), matmul(matmul(H, Z), H), matmul(matmul(H, X), H))
targets = (I, X, Z)
identity_error = max(max_error(actual, expected) for actual, expected in zip(identities, targets))
assert identity_error < 1e-12
basis = ((1, 0), (0, 1))
assert matvec(X, basis[0]) == basis[1] and matvec(X, basis[1]) == basis[0]
assert matvec(Z, basis[0]) == basis[0] and matvec(Z, basis[1]) == (0, -1)
assert matvec(Y, basis[0]) == (0j, 1j)
states = ((1, 0), (0, 1), (scale, scale), (0.6, 0.8j))
composition_error = 0.0
for left, right in ((H, Z), (S, H), (X, S), (Y, H)):
composed = matmul(left, right)
for state in states:
sequential = matvec(left, matvec(right, state))
direct = matvec(composed, state)
composition_error = max(composition_error, *(abs(a - b) for a, b in zip(sequential, direct)))
assert composition_error < 1e-12
witness = (scale, 1j * scale)
assert any(abs(a - b) > 1e-6 for a, b in zip(matvec(matmul(S, H), witness), matvec(matmul(H, S), witness)))
ragged_rejected = False
try:
matvec(((1, 0), (0,)), (1, 0))
except ValueError:
ragged_rejected = True
assert ragged_rejected
print(f"PASS: 11 gate bench verifies {len(gates)} reference matrices and {4 * len(states)} compositions; max identity error={identity_error:.2e}, sequential error={composition_error:.2e}")
Scope boundary
- This chapter does not prove the full spectral theorem or classify all one-qubit unitaries.
- It does not encourage memorizing gate names without verifying their matrices.
Depth commitment. Four gate multiplications, one composition identity, and a matrix-construction exercise.
Practice problem
Derive the matrix of a gate that maps and , then apply it to .
- Deliverable
- Derived matrix, output vector, and normalization/composition checks.
- Pass condition
- The solution identifies H, multiplies exactly, and the test verifies both columns and the submitted output.
Verification record
Expected solution form. Column-construction derivation plus executable matrix assertion.
Model answer. The columns are the declared images of |0> and |1>, so the matrix is H. Applied to (1,i)/sqrt(2), it yields ((1+i)/2,(1-i)/2), a normalized state.
Model result and check. CI compares the matrix and output to exact references up to global phase.
Acceptance test. The solution identifies H, multiplies exactly, and the test verifies both columns and the submitted output.
Companion work
Artifacts for this chapter
These entries resolve to checked-in local source. Commands are reproduced exactly from the chapter manifest, and source-embedded fixtures are exported as direct downloads.
Reproduce or test
python3 tools/validate_briefs.py --briefs data/editorial_briefs_00_35.json --from 0 --through 35 --check-rewritten-sources --execute-artifacts
Provenance
Sources and review
- John Watrous. The Theory of Quantum Information. Cambridge University Press / University of Waterloo. 2018textbook
- Michael A. Nielsen and Isaac L. Chuang. Quantum Computation and Quantum Information. Cambridge University Press. 2010textbook
- John Preskill. Lecture Notes for Physics 219: Quantum Computation. California Institute of Technology. 2018graduate lecture notes
The load-bearing claims in the chapter are mapped inline to this registered source set. A citation supports only the bounded claim beside it.