A7 · Lesson 6 · Lab: vectors and matrices in NumPy
Vectors, matrices and two-ports in code
Everything so far fits on paper: dot products, rotations, cascaded two-ports, areas. Real problems have hundreds of entries, and NumPy is where engineers do this work. In this lab you'll write the first five lessons as code: the angle between vectors, rotation matrices that compose, a ladder of two-ports whose gains follow the Fibonacci numbers, and the area a matrix gives the unit square. Along the way you'll meet the one NumPy habit that catches everyone: * multiplies entry by entry, and @ is matrix multiplication.
- The arrows are and , whose angle and length you set.
- The readouts give and the angle between them, computed the way your code will compute them.
- Turn until the dot product is zero. The angle reads 90°.
Predict
A and B are 2 × 2 NumPy arrays. What does A * B compute?
Matching entries: A * B is the elementwise product, and the matrix product is A @ B. Both are valid, so using the wrong one gives no error, only wrong numbers. With B the identity, A @ B returns A while A * B keeps only A's diagonal.
Name it
Arrays
np.array([3, 4])is a vector andnp.array([[1, 2], [3, 4]])a matrix;A.shapegives its size.A @ Bis the matrix product,A @ va matrix times a vector, andv @ wa dot product.A * B,A + BandA ** 2act entry by entry.A.Tis the transpose,np.eye(n)the identity,np.linalg.norm(v)the length andnp.linalg.det(A)the determinant.
Comparing floating-point results
Computed matrices are rarely exact: comes out as 0.500 000 000 000 000 1. Compare with np.allclose(A, B), which allows a relative error of about plus a tiny absolute one, never with ==.
Angles and areas
- , then
math.acos. Rounding can push the ratio slightly past 1 for parallel vectors, so clip it to in careful code. - The shoelace formula gives the area of a polygon with corners in order: , wrapping round at the end. Applied to the image of the unit square, it should equal .
Worked example
Compute the angle between and in NumPy.
Show the solution
- Compute it in NumPy.
import math
import numpy as np
v, w = np.array([3, 4]), np.array([4, 3])
c = v @ w / (np.linalg.norm(v) * np.linalg.norm(w))
print(math.degrees(math.acos(c))) # 16.26
- Check by hand. The dot product is 24 and both lengths are 5, so and , as in lesson 1.
Answer the angle is 16.26°.
Worked example
A ladder repeats a section of 1 kΩ in series followed by 1 mS in shunt. What is the open-circuit gain of one, two, three and four sections?
Show the solution
- One section's matrix.
- Multiply copies. Multiplying copies and taking gives gains of , , and .
- The pattern. The denominators 2, 5, 13 and 34 are every other Fibonacci number, and each is about 2.6 times the last.
- A long ladder. It attenuates by a fixed ratio per section:
Answer the gains are , , and for one, two, three and four sections.
Check
A = np.array([[a, 2], [3, b]]) with = 2, = 1. What is (A @ A)[0, 1]?
Check
One section has 1 kΩ in series and 0.5 mS in shunt. What is its open-circuit gain?
Check
Write angle(v, w) returning the angle between two NumPy vectors in degrees. Set theta = angle(np.array([3, 4]), np.array([4, 3])).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write rot(t), the 2 × 2 matrix that rotates by t radians. Set R60 = rot(math.pi / 6) @ rot(math.pi / 6) and check it against rot(math.pi / 3).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write series(Z) and shunt(Y) returning transmission matrices, and ladder_gain(n) returning the open-circuit gain of n sections of 1000 Ω in series then 0.001 S in shunt. Set gain = ladder_gain(n) for = 3.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write shoelace(P) returning the area of a polygon whose corners are the columns of a 2 × k array. Map the unit square's corners with ( = 2, = 1) and set area = shoelace(M @ square).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Explain why
Why should you compare computed matrices with np.allclose rather than ==?
Floating-point numbers carry about 16 significant digits, and almost every operation rounds. Values that are equal in exact arithmetic, like and , come out differing in the last digit or two, because is rounded before it's squared. An == test then fails even though the code is right. np.allclose asks whether every pair of entries agrees to within a small relative tolerance, which is the question that matters. The tolerance should match the computation: a well-conditioned 2 × 2 product agrees to , while a solve with a condition number of can only promise about eight digits.
Practice
Keep practicing
6 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.