---
title: "Lab: vectors and matrices in NumPy"
heading: Vectors, matrices and two-ports in code
eyebrow: A7 · Lesson 6 · Lab: vectors and matrices in NumPy
xp: 60
---

::: hook
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.
:::

::: play
- The arrows are $\mathbf{v} = (3, 1)$ and $\mathbf{w}$, whose angle and length you set.
- The readouts give $\mathbf{v}\cdot\mathbf{w}$ and the angle between them, computed the way your code will compute them.
- Turn $\mathbf{w}$ until the dot product is zero. The angle reads 90°.
:::

```sim plot
view: complex
range: 5
axes: x, y
slider: a = 0..355 step 5 = 40
slider: L = 0.5..4 step 0.1 = 3
arrow: 3 + j*1 | label: v
arrow: L*exp(j*a*pi/180) | label: w | color: ch2
readout: dot product = L*(3*cos(a*pi/180) + sin(a*pi/180)) | digits: 4
readout: angle between, degrees = acos((3*cos(a*pi/180) + sin(a*pi/180))/sqrt(10))*180/pi | digits: 4
```

::: predict
## `A` and `B` are 2 × 2 NumPy arrays. What does `A * B` compute?

- [ ] The matrix product $AB$
- [x] The products of matching entries
- [ ] The dot product of their first rows
- [ ] An error, since matrices can't be multiplied with `*`

::: reveal
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.
:::
:::

::: nameit
## Arrays

- `np.array([3, 4])` is a vector and `np.array([[1, 2], [3, 4]])` a matrix; `A.shape` gives its size.
- `A @ B` is the matrix product, `A @ v` a matrix times a vector, and `v @ w` a dot product.
- `A * B`, `A + B` and `A ** 2` act entry by entry.
- `A.T` is the transpose, `np.eye(n)` the identity, `np.linalg.norm(v)` the length and `np.linalg.det(A)` the determinant.

## Comparing floating-point results

Computed matrices are rarely exact: $\cos(\pi/3)$ comes out as 0.500 000 000 000 000 1. Compare with `np.allclose(A, B)`, which allows a relative error of about $10^{-5}$ plus a tiny absolute one, never with `==`.

## Angles and areas

- $\cos\theta = \frac{\mathbf{v}\cdot\mathbf{w}}{|\mathbf{v}||\mathbf{w}|}$, then `math.acos`. Rounding can push the ratio slightly past 1 for parallel vectors, so clip it to $[-1, 1]$ in careful code.
- The **shoelace formula** gives the area of a polygon with corners $(x_i, y_i)$ in order: $\frac12\left|\sum(x_iy_{i+1} - x_{i+1}y_i)\right|$, wrapping round at the end. Applied to the image of the unit square, it should equal $|\det M|$.
:::

::: example
## Compute the angle between $(3, 4)$ and $(4, 3)$ in NumPy.

::: solution
1. **Compute it in NumPy.**

```python
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
```

2. **Check by hand.** The dot product is 24 and both lengths are 5, so $\cos\theta = 0.96$ and $\theta = 16.26°$, as in lesson 1.

**Answer:** the angle is 16.26°.
:::
:::

::: 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?

::: solution
1. **One section's matrix.**
   $$\begin{aligned} &\begin{bmatrix}1 & 1000\\0 & 1\end{bmatrix}\begin{bmatrix}1 & 0\\0.001 & 1\end{bmatrix} \\ &= \begin{bmatrix}2 & 1000\\0.001 & 1\end{bmatrix} \end{aligned}$$
2. **Multiply copies.** Multiplying $n$ copies and taking $1/\mathcal{A}$ gives gains of $\frac12$, $\frac15$, $\frac{1}{13}$ and $\frac{1}{34}$.
3. **The pattern.** The denominators 2, 5, 13 and 34 are every other Fibonacci number, and each is about 2.6 times the last.
4. **A long ladder.** It attenuates by a fixed ratio per section:
   $$1/2.618 = 0.382$$

**Answer:** the gains are $\frac12$, $\frac15$, $\frac{1}{13}$ and $\frac{1}{34}$ for one, two, three and four sections.
:::
:::

::: check
given: a = 2 | 3; b = 1 | 4
answer: 2*a + 2*b
tolerance: 0.5%

## `A = np.array([[a, 2], [3, b]])` with $a$ = {a}, $b$ = {b}. What is `(A @ A)[0, 1]`?

::: right
Right. Row 0 of $A$ times column 1 of $A$: $a \cdot 2 + 2b$ = {answer}.
:::

::: misses
- [4] That's `(A * A)[0, 1]`, the entry squared.
- [any] Not yet. `@` is the matrix product: row 0 times column 1.
:::
:::

::: check
given: R = 1 | 2.2; Y = 0.5 | 2
answer: 1/(1 + R*Y)
tolerance: 0.5%

## One section has {R} kΩ in series and {Y} mS in shunt. What is its open-circuit gain?

::: right
Right. $\mathcal{A} = 1 + RY$, so the gain is {answer}.
:::

::: misses
- [R*Y/(1 + R*Y)] That's the fraction lost across the series resistor.
- [any] Not yet. Multiply the series and shunt matrices and take $1/\mathcal{A}$.
:::
:::

::: check
kind: python

## 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 starter
import math
import numpy as np

def angle(v, w):
    return v @ w

theta = angle(np.array([3, 4]), np.array([4, 3]))
print(theta)
```

```python solution
import math
import numpy as np

def angle(v, w):
    c = v @ w / (np.linalg.norm(v) * np.linalg.norm(w))
    return math.degrees(math.acos(max(-1.0, min(1.0, c))))

theta = angle(np.array([3, 4]), np.array([4, 3]))
print(theta)
```

```python tests
import numpy as np
assert abs(theta - 16.2602047) < 1e-6, f"(3, 4) and (4, 3) are 16.26 degrees apart; got {theta}."
assert abs(angle(np.array([1, 0]), np.array([0, 2])) - 90) < 1e-9, "Perpendicular vectors are 90 degrees apart."
assert abs(angle(np.array([1, 2, 2]), np.array([2, 4, 4]))) < 1e-5, "Parallel vectors are 0 degrees apart (clip the cosine to 1)."
assert abs(angle(np.array([1, 1]), np.array([-1, -1])) - 180) < 1e-5, "Opposite vectors are 180 degrees apart."
```

::: right
Right. Clipping the cosine matters: for parallel vectors rounding can give 1.000 000 000 000 000 2, and `acos` would fail.
:::
:::

::: check
kind: python

## 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 starter
import math
import numpy as np

def rot(t):
    return np.eye(2)

R60 = rot(math.pi / 6) @ rot(math.pi / 6)
print(R60)
```

```python solution
import math
import numpy as np

def rot(t):
    c, s = math.cos(t), math.sin(t)
    return np.array([[c, -s], [s, c]])

R60 = rot(math.pi / 6) @ rot(math.pi / 6)
print(R60)
```

```python tests
import math
import numpy as np
assert np.allclose(R60, rot(math.pi / 3)), "Two 30 degree rotations make one 60 degree rotation."
assert np.allclose(rot(math.pi / 2) @ np.array([1, 0]), [0, 1]), "Rotating (1, 0) by 90 degrees counterclockwise gives (0, 1)."
assert np.allclose(rot(0.7).T @ rot(0.7), np.eye(2)), "A rotation's transpose is its inverse."
```

::: right
Right. The matrix product adds the angles, which is the double-angle formula done by machine.
:::
:::

::: check
kind: python
given: n = 2 | 3 | 4

## 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 $n$ = {n}.

```python starter
import numpy as np

def series(Z):
    return np.eye(2)

def shunt(Y):
    return np.eye(2)

def ladder_gain(n):
    return 0.5 ** n

gain = ladder_gain(n)
print(gain)
```

```python solution
import numpy as np

def series(Z):
    return np.array([[1.0, Z], [0.0, 1.0]])

def shunt(Y):
    return np.array([[1.0, 0.0], [Y, 1.0]])

def ladder_gain(n):
    T = np.eye(2)
    for _ in range(n):
        T = T @ series(1000) @ shunt(0.001)
    return 1 / T[0, 0]

gain = ladder_gain(n)
print(gain)
```

```python tests
want = {1: 1 / 2, 2: 1 / 5, 3: 1 / 13, 4: 1 / 34}
assert abs(gain - want[n]) < 1e-12, f"{n} sections should give {want[n]:.6f}; got {gain}."
assert abs(ladder_gain(1) - 0.5) < 1e-12, "One section is a 1:1 divider, gain 0.5."
assert abs(1 / series(50)[0, 1] - 0.02) < 1e-12 and abs(shunt(0.2)[1, 0] - 0.2) < 1e-12, "series(Z) has Z top right; shunt(Y) has Y bottom left."
```

::: right
Right. The chain's matrix is the product in order from input to output, and the gain follows the Fibonacci numbers.
:::
:::

::: check
kind: python
given: a = 2 | 3; b = 1 | 4

## 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 $M = \begin{bmatrix}a & 1\\0.5 & b\end{bmatrix}$ ($a$ = {a}, $b$ = {b}) and set `area = shoelace(M @ square)`.

```python starter
import numpy as np

square = np.array([[0, 1, 1, 0], [0, 0, 1, 1]])

def shoelace(P):
    return 1.0

M = np.array([[a, 1], [0.5, b]])
area = shoelace(M @ square)
print(area)
```

```python solution
import numpy as np

square = np.array([[0, 1, 1, 0], [0, 0, 1, 1]])

def shoelace(P):
    x, y = P[0], P[1]
    return 0.5 * abs(np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y))

M = np.array([[a, 1], [0.5, b]])
area = shoelace(M @ square)
print(area)
```

```python tests
import numpy as np
assert abs(area - abs(a * b - 0.5)) < 1e-12, f"The image's area is |det M| = {abs(a * b - 0.5)}; got {area}."
assert abs(shoelace(np.array([[0, 4, 1], [0, 1, 3]])) - 5.5) < 1e-12, "The triangle (0, 0), (4, 1), (1, 3) has area 5.5."
```

::: right
Right. The polygon's area and the determinant agree, which is the meaning of the determinant made concrete.
:::
:::

::: explain
## Why should you compare computed matrices with `np.allclose` rather than `==`?

::: model
Floating-point numbers carry about 16 significant digits, and almost every operation rounds. Values that are equal in exact arithmetic, like $R_{30}R_{30}$ and $R_{60}$, come out differing in the last digit or two, because $\cos(\pi/6)$ 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 $10^{-15}$, while a solve with a condition number of $10^8$ can only promise about eight digits.
:::
:::

::: practice

::: check
given: a = 1..9 int; b = 1..9 int
answer: 2*a + 2*b
tolerance: 0

## `(A @ A)[0, 1]` for `A = [[a, 2], [3, b]]` with $a$ = {a}, $b$ = {b}?

::: misses
- [any] $2a + 2b$.
:::
:::

::: check
given: R = 0.1..10; Y = 0.1..10
answer: 1/(1 + R*Y)
tolerance: 0.5%

## Open-circuit gain of {R} kΩ series, {Y} mS shunt?

::: misses
- [any] $\frac{1}{1 + RY}$.
:::
:::
:::
