A matrix becomes a function that deforms space. Establish the correspondence between linear maps and matrices, composition as multiplication, inverses, change of basis and affine maps in homogeneous coordinates. The central idea is that one map has many matrices, and choosing a good basis simplifies the problem.
After this lesson you can
Construct the matrix of a linear map from basis images, including in polynomial spaces.
Prove that map composition corresponds to matrix multiplication in the correct order.
Calculate the representation P⁻¹AP in a new basis and identify invariants such as trace.
Decide whether a transformation is invertible and calculate its inverse in geometric cases.
Model translations and robot-arm poses with homogeneous matrices.
In the first lesson you read the product Ax in two ways: as a combination of columns of A and as a list of dot products with its rows. Both treat the matrix as a static object, a table of numbers. This lesson changes perspective: a matrix A∈Rm×n is a functionx↦Ax that takes vectors from Rn and returns vectors in Rm, and what matters is what it does to space.
That change of view appears as soon as you build something real:
A neural-network layer computes h=σ(Wx+b). The part x↦Wx is a linear map from Rdin to Rdout, and with bias b it is affine. Chaining two layers without a nonlinearity between them gives W2(W1x)=(W2W1)x: another linear map, one layer disguised as two. This is the linear collapse of depth, clear in one line once you know composition is multiplication.
A robotic arm rotates each joint and advances along each link. Gripper position and orientation are the product of one matrix per joint, and factor order decides whether the robot picks up the part or hits the table.
A financial factor model writes the systematic part of returns for N assets as r=Bf, a linear function of K risk factors. If factors are replaced by combinations of themselves, f=Pg with P invertible, loadings become BP and the model is unchanged: only input coordinates have changed.
The final example contains the lesson’s central idea. A linear map is a geometric object; its matrix only describes it in specific coordinates. The same map has many matrices, one per choice of bases, and a good basis can turn a dense matrix diagonal. This idea, introduced here, underlies eigenvectors, SVD and the Fourier transform.
Linearity: two rules decide everything
Three immediate consequences worth keeping at hand:
T(0)=0. Take c=0 in the second rule. A function that moves the origin is not linear, however simple.
T preserves any linear combination:T(∑icivi)=∑iciT(vi), by induction on the number of summands.
Lines map to lines or points. Line {p+td:t∈R} maps to {T(p)+tT(d):t∈R}, another line, or a single point if T(d)=0. Parallel lines (same d) map to parallel lines, possibly coincident, or all to points if T(d)=0; equally spaced points p+kd map to equally spaced points. A grid therefore becomes a grid of parallelograms.
In the plane, consequence 2 has a striking effect. Every vector is x=x1e1+x2e2, so T(x)=x1T(e1)+x2T(e2): if you know where arrows e1 and e2 go, you know where the entire plane goes. Try it.
InteractiveDeform the plane with two arrows
T(x)=1.50[1.500.50]+1.00[−0.501.00]=[1.751.75]
The same coordinates (x1,x2), now read on the transformed grid: each column is underlined in its arrow color.
Matrix A=[T(e1)T(e2)]
Plane
x(1.50, 1.00)
T(x)=Ax(1.75, 1.75)
detA (signed area)1.75
Drag the tips of T(e1) and T(e2): the grid, letter F and unit circle follow because T(x)=x1T(e1)+x2T(e2). Also drag x and compare its position in the original grid with that of T(x) in the deformed grid. Select “Unit square” to see the cell formed by the columns, with area ∣detA∣. Finally, align the two arrows.
Coordinates travel with the grid.T(x) occupies exactly the position in the deformed grid that x occupied in the original: the path to T(x) follows x1 times T(e1) (orange segment), then x2 times T(e2) (aqua segment).
The unit circle becomes an ellipse as long as T does not collapse the plane. That it is always an ellipse with computable axes is the geometric content of the SVD.
The F can be reversed. This happens exactly when the shortest rotation from T(e1) to T(e2) is clockwise, unlike from e1 to e2. The sign of the determinant, detA=a11a22−a12a21, detects it; its absolute value is also the area multiplication factor: each deformed grid cell measures ∣detA∣.
Aligning the arrows collapses the whole plane onto a line. Infinitely many vectors then go to the same point: the dashed red line maps entirely to 0 (in “Aligned columns,” x itself lies on it), and each parallel to that line maps to one point. T ceases to be injective and cannot be undone. We return to this with inverses.
What you just checked by dragging two arrows is a theorem valid in any vector space: a linear map is determined by very little information, which can be chosen freely.
Proof
Uniqueness. Every v∈V has a unique expression v=∑jcjvj: its coordinates in the basis. If T is linear and T(vj)=wj, consequence 2 forces T(v)=∑jcjwj. Thus two linear maps agreeing on a basis agree on all V.
Existence. The preceding formula is the only possible candidate. You prove it really defines a linear map in the next exercise.
∎
ProofExistence, step by step
Prove: Given a basis (v1,…,vn) of V and arbitrary vectors w1,…,wn∈W, there exists a linear map T:V→W with T(vj)=wj for every j.
0
Every v∈V is uniquely written as v=∑jcjvj.
Step 1 of 4. How do you define T?
The practical consequence is huge. To describe a linear map Rn→Rm, specify where the n standard basis vectors go: n vectors in Rm, mn numbers total. In the plane, these are the figure’s two arrows.
The matrix of a linear map
The theorem says a linear map is equivalent to a list of images of basis vectors. If those images are written in coordinates of a codomain basis, we obtain a table of numbers.
The coefficient of wi is component i of [T]C←Bc, with c=[v]B=(c1,…,cn), and coordinates in C are unique.
∎
Notation C←B reads right to left, like the matrix itself: a vector enters in coordinates of B and exits in coordinates of C. In Rn with standard bases it is omitted, and the definition reduces to a sentence worth remembering:
Also notice shapes. A∈Rm×n has one column per input dimension and one row per output dimension: it represents a map Rn→Rm, again right to left. This is PyTorch’s convention: a layer nn.Linear(3, 2) with 3 inputs and 2 outputs stores a weight matrix of shape (2, 3).
The definition works equally in spaces other than Rn, where it becomes clear that the matrix is only a representation.
The matrix depends on the chosen basis. In basis T=(1,x,2x2,6x3) each vector is the derivative of the next, so D sends each basis vector to its predecessor and its matrix has ones on the superdiagonal: a pure coordinate shift. Same map, different and simpler matrix.
Column j+1 (j=0,…,3): coordinates of D(xj)=jxj−1. Thus the superdiagonal is 1,2,3.
Basis of P3
p(x)=0.50−1.50x+0.50x3p′(x)=−1.50+1.50x2
Each coordinate of p has a slider. The matrix of D multiplies coordinates of p and returns those of p′, whose graph is drawn in magenta. Change basis: the polynomial and its derivative stay fixed, but their coordinates and the matrix of D change. In the Legendre basis used in the second lab, the matrix no longer has a single diagonal.
Composition: why matrix multiplication works as it does
If T:V→W and S:W→U are linear, their composition S∘T:V→U, (S∘T)(v)=S(T(v)), is linear too: S(T(au+bv))=S(aT(u)+bT(v))=aS(T(u))+bS(T(v)). The question is what its matrix is.
Proof
Let S=[S]D←C and T=[T]C←B. Column j of [S∘T]D←B contains coordinates of S(T(vj)) in D. Applying the preceding theorem twice,
[S(T(vj))]D=S[T(vj)]C=S(columna j de T).
By the columnwise reading of matrix multiplication, column j of ST is exactly S times column j of T. The matrices agree column by column.
∎
Read in reverse, the theorem explains what was a convention in the first lesson: the product is defined row by column because it is the only rule making the matrix of a composition the product of the matrices. The indexed proof is in the exercises.
Four everyday facts follow from this theorem:
Associativity for free.(AB)C=A(BC) because both are the matrix of the same composition, and function composition is associative. No indices needed.
Noncommutativity.S∘T and T∘S are generally different maps, so ST=TS. Sometimes both are not even defined.
Shapes.S∘T exists only if the codomain of T is the domain of S. For matrices, (m×p)(p×n)=m×n: the inner index is the intermediate-space dimension.
Reading order. In ABx=A(Bx), B acts first. Matrices apply right to left, like the functions in f(g(x)).
A concrete example: with rotation R=R30° and shear S=[1011],
SR rotates first and then shears; RS does the reverse, and they are different maps. Notice, however, that both have the same trace, 2.232. This is not a coincidence, as you will prove below.
InteractiveOrder matters: AB versus BA
F original
F after the first transformation
F at the end
1st B→2nd A
AB=[0.870.500.371.37]
1st A→2nd B
BA=[1.370.500.370.87]
final
Transformation A
A=[0.870.50−0.500.87]
Transformation B
B=[1.000.001.001.00]
∥AB−BA∥F0.707
tr(AB) and tr(BA)2.232 = 2.232
det(AB) and det(BA)1.000 = 1.000
AB=BA: the same pair of transformations in another order gives a different map.
The two panels apply the same transformations A and B in opposite orders. Press play: the first applies B first, yielding AB; the second applies A first, yielding BA. The transformation applied first is always on the right of the product, and the dashed F marks the intermediate state. Find commuting pairs: two rotations, uniform scaling with any other, two projections onto the same line. Notice the readouts: although AB=BA, their traces and determinants always agree.
Gallery of the plane
With the rule “columns are the images of the axes,” basic planar transformations can be written from memory. They appear everywhere: vision data augmentation, graphics, robotics and, as numerical algorithm building blocks, Householder reflections and Givens rotations.
Transformation
Matrix
What it does
Invertible?
Scaling
[a00b]
stretches axis x by a and axis y by b
if ab=0, with inverse diag(1/a,1/b)
Shear
[10k1]
shifts each horizontal line k times its height
always: replace k with −k
Rotation
[cosθsinθ−sinθcosθ]
rotates by angle θ
always: Rθ−1=R−θ=Rθ⊤
Reflection
[cos2φsin2φsin2φ−cos2φ]
reflects across the line at angle φ
always: it is its own inverse
Projection
[cos2φcosφsinφcosφsinφsin2φ]
flattens the plane onto the line at angle φ
never
The last two follow by decomposing each vector into parts along and perpendicular to the line. Try to predict each step before revealing it:
x=(u⊤x)u+(x−(u⊤x)u)
With unit u=(cosφ,sinφ), the first summand lies on the line and the second is perpendicular: its dot product with u is u⊤x−(u⊤x)(u⊤u)=0.
1/5
Expressions P=uu⊤ and H=2uu⊤−I yield almost without calculation the properties discovered in the next interactive:
P2=u(u⊤u)u⊤=P, because u⊤u=1: projecting twice is projecting once (projection is idempotent).
H2=4P2−4P+I=I: reflecting twice leaves everything as it was (reflection is an involution).
RαRβ=Rα+β, because rotating β and then α equals rotating α+β. Writing entries on both sides gives the sine and cosine addition formulas, so they need not be memorized.
HφHψ=R2(φ−ψ): two reflections compose to a rotation by twice the angle between their lines, so any rotation is a product of two reflections. This idea reappears in Householder reflections.
InteractiveGallery: apply, apply twice, undo
F original
Transformed F
image of the unit circle
line at angle φ
View
T=[0.500.870.87−0.50]
detT−1.00
Invertible?yes
Preserves lengths?yes
Reflects across the line at angle φ: lengths are preserved but orientation reverses (the F is mirrored).
Choose a transformation and parameter. “Twice” shows T2 and “Undo” applies T−1 to the result. Rotations add angles, reflections return to the starting point, and projections do not change when repeated. Which cannot be undone? For projection, each dashed line collapses onto its filled point: given the result there is no way to tell which point it came from.
Projection is the only gallery transformation that cannot be undone, along with scalings having a zero factor: diag(0,b) projects onto axis y then scales by b, and with both factors zero everything goes to the origin. The reason is geometric: projection sends each line perpendicular to the projection line to one point, so given Px there is no way to know which x it came from. What is lost is exactly that perpendicular direction, the null space of P.
The inverse
Proof
If B and C are inverses of A, then B=B(AC)=(BA)C=C.
Let w1,w2∈W and vi=T−1(wi). By linearity of T, T(av1+bv2)=aw1+bw2, and applying T−1 to both sides gives T−1(aw1+bw2)=aT−1(w1)+bT−1(w2). Matrix equality follows from composition: [T−1]B←C[T]C←B=[T−1∘T]B←B=[idV]B←B=I and, in the other order, [T]C←B[T−1]B←C=[idW]C←C=I.
(AB)(B−1A−1)=A(BB−1)A−1=AA−1=I, and similarly on the other side. For the transpose, A⊤(A−1)⊤=(A−1A)⊤=I.
∎
Formula (AB)−1=B−1A−1 is the socks-and-shoes rule: if you put on socks first (B) and shoes second (A), undoing it means removing shoes first. Getting this order wrong is a common error when differentiating with matrices.
An invertible map takes a basis of its domain to a basis of its codomain, because a linear bijection preserves independence and spanning. Therefore dimV=dimW: only square matrices can be invertible. For these there are many equivalent ways to say “invertible,” and the list grows throughout the module.
Proof
We prove two chains of implications through (4).
(1)⇒(5) and (1)⇒(6): take B=C=A−1.
(5)⇒(2): if Ax=0, then x=BAx=B0=0.
(6)⇒(3): x=Cb satisfies Ax=ACb=b.
(2)⇒(4): Ax=∑jxjaj is a combination of columns aj. Its vanishing only for x=0 means the n columns are linearly independent, and n independent vectors in a space of dimensionn form a basis.
(3)⇒(4): every b is a combination of columns, which therefore span Rn, and n spanning vectors of a space of dimension n form a basis.
(4)⇒(1): if columns form a basis, every b has unique coordinates x in it, meaning Ax=b has a unique solution. The map is bijective and, by the previous proposition, invertible.
∎
Two frequently used consequences. First, for square matrices, a one-sided inverse is two-sided; if B has BA=I, then AB=I. This is false for rectangular matrices: with A=[10] and B=[10] we have BA=1, but AB=[1000]. Second, for a square matrix, injective, surjective and bijective are equivalent, unlike arbitrary functions. The list will grow with rank (rankA=n), determinant (detA=0) and eigenvalues (none zero).
In dimension 2 the inverse has a closed formula:
[acbd]−1=ad−bc1[d−c−ba],si ad−bc=0,
which is checked by multiplication: [acbd][d−c−ba]=(ad−bc)I. The number ad−bc is the determinant, the signed area of the parallelogram formed by the columns, and vanishes exactly when columns align: the collapse you saw by aligning the arrows in the first figure.
Change of basis: same map, different matrix
You have seen that a map’s matrix depends on bases. Now measure how, and use it. First work in Rn with an operator T(x)=Ax written in the standard basis.
Let B=(b1,…,bn) be another basis and P=[b1⋯bn] the matrix whose columns are those vectors in standard coordinates. If c=[x]B are coordinates of x in B, then x=∑jcjbj=Pc. That is,
x=P[x]B,[x]B=P−1x.
P is invertible because its columns form a basis. P translates new coordinates to standard coordinates, and P−1 translates standard to new: that dictionary is change of basis. For example, with b1=(1,1) and b2=(1,−1), vector x=(3,1) has coordinates [x]B=(2,1) because 2(1,1)+1(1,−1)=(3,1).
What matrix represents T if everything is measured in basis B? Given a vector in coordinates of B, convert to standard with P, apply A and return to B with P−1:
[T(x)]B=P−1AP[x]B⟹[T]B=P−1AP.
The diagram summarizes the path; both routes from the lower left to the lower right give the same result:
where columns of P are vectors of B′ written in coordinates of B.
If the map goes between different spaces, T:V→W, two bases must change, each with its transition matrix: P=[idV]B←B′ in the domain and Q=[idW]C←C′ in the codomain. The same argument gives
Two matrices m×n related this way, with P and Q independently invertible, are equivalent. This offers much more freedom than similarity, where one P changes input and output together, and simplifies much further: every matrix of rankr is equivalent to [Ir000]. Choose a basis of V whose last n−r vectors span the kernel, which has that dimension by the rank–nullity theorem. Images of the first r span the image of T, which has dimension r, so they are independent and can be extended to a basis of W. Thus, up to equivalence, a matrix has one invariant: its rank. If both bases must also be orthonormal, the best attainable form is a diagonal of singular values, the SVD.
Similarity is an equivalence relation (use P=I, P−1 and the product of two transition matrices), and matrices are similar exactly when they represent the same operator in two bases. Thus any quantity depending only on the operator must agree for similar matrices: an invariant. The first and cheapest to calculate is trace.
It is linear, tr(aA+bB)=atrA+btrB, satisfies trA⊤=trA and, above all, has this property:
Apply this to factors P−1 and AP: tr(P−1(AP))=tr((AP)P−1)=trA. A guided version is in the exercises.
∎
Trace is invariant under cyclic permutations of a product, tr(ABC)=tr(BCA)=tr(CAB), not arbitrary permutations: with A=[0010], B=A⊤ and C=[1000] we have tr(ABC)=1 and tr(BAC)=0. This manipulation rule, the trace trick, is a main tool of matrix calculus.
Because it is basis-independent, trace is well defined for any operator T:V→V: trT=tr[T]B in any basis. The same holds for determinant, rank and eigenvalues. What does it measure? Two answers proved later: it is the sum of eigenvalues, and the rate at which volume changes under a small deformation, det(I+εA)=1+εtrA+O(ε2). Thus the divergence of linear velocity field x˙=Ax is trA. What does not survive a basis change is individual entries, even diagonal entries separately (only their sum), or matrix symmetry unless the basis change is orthonormal.
Find the directions that A only stretches and align b1 and b2 with them.
In the first panel, A acts in the standard basis and the blue lattice is basis B=(b1,b2). The second shows the same thing in coordinates of B, where the matrix is P−1AP and that lattice is the ordinary grid. Drag b1 and b2 until each dashed arrow lies on its vector's line: the second panel's matrix becomes diagonal. Trace and determinant never change. Then try shear and rotation.
What the interactive shows becomes theorems. The symmetric matrix diagonalizes with two perpendicular directions (the spectral theorem). The one with oblique directions also diagonalizes, but in a nonorthogonal basis. Shear has one invariant direction, which is fixed (factor 1), and the best attainable form is triangular (the Jordan form). Rotation has no real invariant direction because its eigenvalues are complex.
Affine maps and homogeneous coordinates
If b=0, f is not linear because f(0)=b. But it preserves nearly all linear geometry: it preserves affine combinations, those whose coefficients sum to one. If ∑iλi=1,
It therefore maps lines to lines (or points if their direction lies in the kernel of A), preserves parallelism and ratios along a line (a segment’s midpoint maps to its image’s midpoint), and maps centers of mass to centers of mass. The origin is the only thing it does not preserve.
Composing affine maps is cumbersome: f2(f1(x))=A2A1x+(A2b1+b2). With ten robot joints, tracking constant terms becomes error-prone. Homogeneous coordinates solve this by adding a constant coordinate equal to 1:
[Ax+b1]=A~∈R(m+1)×(n+1)[A0⊤b1][x1].
The affine map on Rn is the restriction of a linear map on Rn+1 to hyperplane xn+1=1, after which everything you know about matrices works:
Composition is multiplication:[A20⊤b21][A10⊤b11]=[A2A10⊤A2b1+b21], the earlier formula without bookkeeping.
Inversion is inversion: if A is invertible, [A0⊤b1]−1=[A−10⊤−A−1b1]. Multiply to check.
Points and directions distinguish themselves. A point ends in 1; a direction, the difference of two points, ends in 0. Translations therefore do not affect directions: A~(d,0)=(Ad,0).
The most important robotics case is planar rigid motions: a rotation followed by a translation, [R0⊤t1] with R a rotation matrix. They form a group, the special Euclidean group SE(2): the product of two rigid motions is another, as is the inverse [R⊤0⊤−R⊤t1]. In space, SE(3) uses matrices 4×4, the mathematics of robots, drones and graphics engines.
A planar two-link arm rotates its first joint by θ1 and advances the first link’s length L1; there it rotates θ2 relative to the preceding link and advances L2. Each joint is a matrix in SE(2):
Mi converts coordinates from reference frame {i}, attached to the end of link i, into coordinates of the previous frame {i−1}. The gripper is the origin of {2}, so in base coordinates it is at
and its orientation is θ1+θ2, the angle of the rotation block of M1M2. The product has two equivalent readings. Right to left: a point in {2} is converted to {1} with M2 and then to the base with M1. Left to right: “rotate θ1, advance L1, rotate θ2 relative to where you are, advance L2,” each motion relative to the current frame.
Each joint is a homogeneous matrix Mi (rotate θi and advance Li), and gripper pose is the product M1M2, whose last column is position. Move the angles or drag the gripper. “Wrong order” draws the arm actually computed by M2M1, with joints exchanged, and “Reachable region” shows the annulus ∣L1−L2∣≤∥p∥≤L1+L2.
Implementation: a small 2D transformation engine
Write everything above from scratch in NumPy: gallery transformations, homogeneous coordinates and arm forward kinematics. One convention before starting: the text uses column vectors and writes Mx, but code commonly stores many points as rows of an array of shape (k,2). The same operation is then pts @ M.T, because (Mx)⊤=x⊤M⊤.
[ ]Planar transformations and homogeneous coordinatesBrowser
import numpy as np
import matplotlib.pyplot as plt
def rot(theta):
c, s = np.cos(theta), np.sin(theta)
return np.array([[c, -s], [s, c]])
def shear(k):
return np.array([[1.0, k], [0.0, 1.0]])
def scale(a, b):
return np.diag([a, b]).astype(float)
def reflect(phi):
"""Reflexión respecto a la recta de ángulo phi: H = 2 u uᵀ − I."""
u = np.array([np.cos(phi), np.sin(phi)])
return 2 * np.outer(u, u) - np.eye(2)
def proj(phi):
"""Proyección ortogonal sobre la recta de ángulo phi: P = u uᵀ."""
u = np.array([np.cos(phi), np.sin(phi)])
return np.outer(u, u)
def hom(A=np.eye(2), t=(0.0, 0.0)):
"""Matriz homogénea 3x3 de la aplicación afín x -> A x + t."""
M = np.eye(3)
M[:2, :2] = A
M[:2, 2] = t
return M
def apply(M, pts):
"""Aplica M (2x2 lineal o 3x3 homogénea) a puntos guardados como FILAS de un array (k, 2)."""
pts = np.asarray(pts, dtype=float)
if M.shape == (2, 2):
return pts @ M.T # fila x: (M x)ᵀ = xᵀ Mᵀ
ph = np.hstack([pts, np.ones((len(pts), 1))])
return (ph @ M.T)[:, :2] # en una afín la última coordenada sigue valiendo 1
F = np.array([[0, 0], [.36, 0], [.36, .62], [.86, .62], [.86, .92], [.36, .92],
[.36, 1.28], [1.12, 1.28], [1.12, 1.6], [0, 1.6]]) + [0.3, 0.2]
casos = {
"rotación 60°": rot(np.pi / 3),
"cizalla k = 1": shear(1.0),
"reflexión φ = 30°": reflect(np.pi / 6),
"proyección φ = 30°": proj(np.pi / 6),
"giro 90° + traslación": hom(rot(np.pi / 2), (2.5, -0.5)),
}
fig, axes = plt.subplots(1, len(casos), figsize=(13, 3), sharex=True, sharey=True)
cerrar = lambda P: np.vstack([P, P[:1]])
for ax, (nombre, M) in zip(axes, casos.items()):
ax.plot(*cerrar(F).T, color="gray", lw=1, ls="--")
G = apply(M, F)
ax.fill(*G.T, alpha=0.25)
ax.plot(*cerrar(G).T, lw=1.5)
ax.axhline(0, lw=0.6, color="gray"); ax.axvline(0, lw=0.6, color="gray")
ax.set_title(nombre, fontsize=10); ax.set_aspect("equal")
axes[0].set_xlim(-2.2, 3.9); axes[0].set_ylim(-1.6, 2.4)
plt.tight_layout()
plt.show()
With the engine written, every claim from the gallery and inverse section becomes a one-line check:
[ ]Composition, order and inversesBrowser
R, S = rot(np.pi / 6), shear(1.0)
print("S R (primero R, después S):\n", (S @ R).round(3))
print("R S (primero S, después R):\n", (R @ S).round(3))
print("¿Conmutan?", np.allclose(S @ R, R @ S), " trazas:", np.trace(S @ R).round(3), np.trace(R @ S).round(3))
th, phi, psi = 0.7, 0.3, 0.1
H, P = reflect(phi), proj(phi)
t = np.array([1.0, 2.0])
comprobaciones = {
"R(a) R(b) = R(a + b)": np.allclose(rot(0.4) @ rot(th), rot(0.4 + th)),
"R⁻¹ = Rᵀ": np.allclose(np.linalg.inv(rot(th)), rot(th).T),
"H² = I": np.allclose(H @ H, np.eye(2)),
"P² = P": np.allclose(P @ P, P),
"H(φ) H(ψ) = R(2(φ − ψ))": np.allclose(reflect(phi) @ reflect(psi), rot(2 * (phi - psi))),
"(R S)⁻¹ = S⁻¹ R⁻¹": np.allclose(np.linalg.inv(R @ S), np.linalg.inv(S) @ np.linalg.inv(R)),
"inversa afín [Rᵀ, −Rᵀt]": np.allclose(np.linalg.inv(hom(R, t)), hom(R.T, -R.T @ t)),
}
for nombre, ok in comprobaciones.items():
print(f"{nombre:26s} {ok}")
print("det P =", round(np.linalg.det(P), 12), "-> la proyección no tiene inversa")
Forward kinematics of a three-link arm is a loop that right-multiplies one matrix per joint. Compare it with the closed formula p=∑iLi(cosϕi,sinϕi), where ϕi=θ1+⋯+θi is the absolute orientation of link i:
[ ]Forward kinematics with homogeneous matricesBrowser
def joint(theta, L):
"""Articulación: girar theta y avanzar L a lo largo del eslabón girado, Rot(θ) Trans(L, 0)."""
return hom(rot(theta)) @ hom(np.eye(2), (L, 0.0))
def forward_kinematics(thetas, lengths):
"""Base, articulaciones y pinza en coordenadas de la base, componiendo matrices homogéneas."""
T = np.eye(3)
puntos = [T[:2, 2].copy()]
for theta, L in zip(thetas, lengths):
T = T @ joint(theta, L) # por la DERECHA: cada movimiento es relativo al eslabón anterior
puntos.append(T[:2, 2].copy())
return np.array(puntos), T
thetas = np.radians([30.0, 45.0, -60.0])
lengths = np.array([2.0, 1.5, 1.0])
puntos, T = forward_kinematics(thetas, lengths)
phis = np.cumsum(thetas) # orientación absoluta de cada eslabón
p_cerrada = np.array([np.sum(lengths * np.cos(phis)), np.sum(lengths * np.sin(phis))])
print("pinza con matrices: ", puntos[-1].round(6))
print("pinza, fórmula cerrada:", p_cerrada.round(6))
print("orientación de la pinza:", np.degrees(np.arctan2(T[1, 0], T[0, 0])).round(6), "grados")
fig, ax = plt.subplots(figsize=(5.5, 4))
for th2 in np.radians(np.linspace(-120, 120, 9)):
q, _ = forward_kinematics([thetas[0], th2, thetas[2]], lengths)
ax.plot(*q.T, "-o", ms=3, lw=1.2, color="gray", alpha=0.45)
ax.plot(*puntos.T, "-o", ms=4, lw=2.5, label="θ = (30°, 45°, −60°)")
ax.set_aspect("equal"); ax.legend(loc="upper left"); ax.set_title("Barrido de θ₂ con θ₁ y θ₃ fijos")
plt.show()
Read a map in the right basis
The second lab returns to polynomials, now of degree ≤4, to see the central idea with real operators. Construct three matrices from the definition (column j = coordinates of the image of the j-th monomial): derivative D(p)=p′; Legendre operator L(p)=((1−x2)p′)′, arising when solving the potential equation in spherical coordinates; and E(p)=(xp)′, which is invertible. Generate Legendre polynomials P0,…,P4 from scratch with Bonnet’s recurrence, (k+1)Pk+1=(2k+1)xPk−kPk−1, rewrite the three matrices in that basis with P−1AP, and check trace and determinant are unchanged.
[ ]The derivative and Legendre operator in two basesBrowser
from numpy.polynomial import polynomial as Poly
from numpy.polynomial import legendre as Leg
n = 5 # polinomios de grado ≤ 4: base de monomios 1, x, ..., x⁴
def a_n(c):
"""Rellena o recorta un vector de coeficientes a longitud n."""
out = np.zeros(n)
c = np.atleast_1d(c)[:n]
out[:len(c)] = c
return out
def matriz_en_monomios(op):
"""Columna j = coeficientes de op(x^j): la definición de la matriz de una aplicación lineal."""
return np.column_stack([a_n(op(np.eye(n)[j])) for j in range(n)])
D = matriz_en_monomios(Poly.polyder) # p -> p'
L = matriz_en_monomios(lambda c: Poly.polyder(Poly.polymul([1, 0, -1], Poly.polyder(c)))) # p -> ((1 − x²) p')'
E = matriz_en_monomios(lambda c: Poly.polyder(Poly.polymulx(c))) # p -> (x p)', invertible
# base de Legendre desde cero, con la recurrencia de Bonnet: (k+1) P_{k+1} = (2k+1) x P_k − k P_{k−1}
leg = [a_n([1.0]), a_n([0.0, 1.0])]
for k in range(1, n - 1):
leg.append(((2 * k + 1) * a_n(Poly.polymulx(leg[k])) - k * leg[k - 1]) / (k + 1))
Pleg = np.column_stack(leg) # columna k = coeficientes en monomios de P_k
print("coincide con numpy.polynomial.legendre:",
np.allclose(Pleg, np.column_stack([a_n(Leg.leg2poly(np.eye(n)[k])) for k in range(n)])))
np.set_printoptions(precision=3, suppress=True)
for nombre, M in [("D", D), ("L", L), ("E", E)]:
Mb = np.linalg.solve(Pleg, M @ Pleg) # P⁻¹ M P sin formar P⁻¹
print(f"{nombre} en monomios:\n{M}\n{nombre} en Legendre:\n{Mb}")
print(f" traza {np.trace(M):7.3f} | {np.trace(Mb):7.3f} det {np.linalg.det(M):8.3f} | {np.linalg.det(Mb):8.3f}\n")
rng = np.random.default_rng(0)
A = rng.standard_normal((n, n))
Q = rng.standard_normal((n, n)) # invertible con probabilidad 1
B = np.linalg.solve(Q, A @ Q) # B = Q⁻¹ A Q
print("matriz aleatoria: traza", np.trace(A).round(10), np.trace(B).round(10),
"| det", np.linalg.det(A).round(10), np.linalg.det(B).round(10))
print("polinomio característico igual:", np.allclose(np.poly(A), np.poly(B)))
Read the output carefully. In monomials, L is upper triangular: L(xk)=−k(k+1)xk+k(k−1)xk−2. In the Legendre basis it is diagonal, with entries 0,−2,−6,−12,−20: each Pk satisfies L(Pk)=−k(k+1)Pk, the Legendre differential equation, so Legendre polynomials are directions that L only stretches. Trace −40 is the same in both bases, as is the determinant (zero because constants go to zero). E does the opposite: diagonal in monomials because E(xk)=(k+1)xk, triangular in Legendre. The right basis depends on the operator. Since E is invertible, determinant invariance has a nontrivial value: 120=5! in both bases, with trace 15. The derivative, by contrast, cannot be diagonalized in any basis: it is nilpotent, and in Legendre basis appears as Pk′=∑(2j+1)Pj, summing over j<k with k−j odd. The last line confirms with a random matrix that not only trace and determinant but the entire characteristic polynomial is invariant under similarity.
The professional version
In practice you do not write rot or hom by hand in every project, but libraries do exactly the same thing, and understanding their relation to theory prevents silent errors. The first check measures the inverse-section warning on an ill-conditioned matrix:
[ ]Solve without inversionBrowser
import scipy.linalg as sla
rng = np.random.default_rng(0)
m = 200
U, _ = np.linalg.qr(rng.standard_normal((m, m)))
V, _ = np.linalg.qr(rng.standard_normal((m, m)))
A = U @ np.diag(np.logspace(0, -12, m)) @ V.T # matriz mal condicionada (κ = 10¹²)
x_true = rng.standard_normal(m)
b = A @ x_true
x_solve = np.linalg.solve(A, b) # LU con pivoteo (LAPACK)
x_inv = np.linalg.inv(A) @ b # inversa explícita: lo que NO se hace
lu = sla.lu_factor(A) # factorizar una vez...
x_lu = sla.lu_solve(lu, b) # ...y resolver para cada lado derecho
residuo = lambda x: np.linalg.norm(A @ x - b) / (np.linalg.norm(A) * np.linalg.norm(x))
for nombre, x in [("solve", x_solve), ("inv(A) @ b", x_inv), ("lu_solve", x_lu)]:
err = np.linalg.norm(x - x_true) / np.linalg.norm(x_true)
print(f"{nombre:11s} residuo relativo {residuo(x):.1e} error relativo {err:.1e}")
All three solutions have error far above machine precision because the problem is ill-conditioned and no algorithm can avoid that. But solve and lu_solve give residual ∥Ax−b∥ on the order of machine precision (they exactly solve a nearby problem), while using the inverse multiplies that residual by many orders of magnitude and worsens error. The condition number explains this fully.
The second check is trickier. scipy.ndimage.affine_transform applies affine transformations to images, the basis of vision data augmentation. But it has two conventions different from the text: it uses (row, column) indices with rows downward, and requires the inverse map, from each output pixel to where the input must be read. Both are handled by what you just learned: a coordinate change C and an inverse.
[ ]Rotate an image with scipy.ndimageBrowser
from scipy import ndimage
img = np.zeros((64, 64)) # índices (fila, columna): filas hacia ABAJO
img[14:50, 20:27] = 1 # trazo vertical de la F
img[14:21, 20:46] = 1 # brazo superior
img[29:35, 20:40] = 1 # brazo central
cy = cx = 31.5
# C: (fila, columna, 1) -> (x, y, 1) con origen en el centro y el eje y hacia arriba (un cambio de coordenadas)
C = np.array([[0.0, 1.0, -cx],
[-1.0, 0.0, cy],
[0.0, 0.0, 1.0]])
G = hom(rot(np.radians(30))) # giro antihorario de 30° en coordenadas (x, y)
# affine_transform pide la aplicación INVERSA, de píxeles de salida a píxeles de entrada:
# o (índice) -> C o (punto) -> G⁻¹ C o (punto de origen) -> C⁻¹ G⁻¹ C o (índice de entrada)
M_pull = np.linalg.inv(C) @ np.linalg.inv(G) @ C
bien = ndimage.affine_transform(img, M_pull, order=1)
mal = ndimage.affine_transform(img, G, order=1) # la matriz "directa", tal cual
fig, axes = plt.subplots(1, 3, figsize=(9, 3.2))
for ax, im, titulo in zip(axes, [img, bien, mal], ["original", "C⁻¹ G⁻¹ C (correcto)", "G tal cual (incorrecto)"]):
ax.imshow(im, cmap="gray_r", vmin=0, vmax=1)
ax.set_title(titulo, fontsize=10)
ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout()
plt.show()
The correct matrix, C−1G−1C, is a similarity transform: the same rotation G−1 written in index coordinates. Passing G directly rotates in the opposite direction around the upper-left corner, the index origin, so the F shifts and part leaves the frame.
Finally, PyTorch. A layer nn.Linear is an affine map with the matrix stored as in the text, shape (output, input), but the data batch is in rows, so it calculates X @ W.T + b:
import torchlin = torch.nn.Linear(in_features=3, out_features=2)print(lin.weight.shape) # torch.Size([2, 3]): W ∈ R^{2×3}, aplicación R³ -> R²X = torch.randn(5, 3) # lote de 5 vectores de entrada, uno por FILAY = lin(X) # forma (5, 2)print(torch.allclose(Y, X @ lin.weight.T + lin.bias)) # True: cada fila es W x + b
Keep this correspondence in mind when reading code: with row vectors, applying A then B is written x @ A.T @ B.T, left to right, while on paper it is BAx, right to left. Networks use this same batch shape convention.
Common mistakes
Exercises
QuizLinear or not?
Which functions are linear? (A and b=0 are fixed.)
More than one answer may be correct.
QuizRotate first, then reflect
You want to rotate 90° counterclockwise and then reflect across the x-axis. Which matrix performs the composition?
QuizTwo layers that are one
A batch X∈RB×3, with one example per row, passes through nn.Linear(3, 5) and then nn.Linear(5, 2), both without bias and without an activation between them. Their PyTorch-style stored weights are W1 and W2. Which weights W must one bias-free nn.Linear(3, 2) have to compute exactly the same thing?
NumericTrace of a rotated shear
Let S=[1021] and R be rotation by 30°. Calculate tr(R−1SR).
NumericInverse of a product
Let A=[2111] and B=[1021]. Calculate entry (1,2) (row 1, column 2) of (AB)−1.
NumericA matrix in another basis
Let A=[3012] and basis b1=(1,1), b2=(1,2). Calculate entry (1,2) of the matrix of x↦Ax in basis B=(b1,b2).
QuizWhich transition matrix?
Columns of Q are the standard basis vectors written in coordinates of basis B, so [x]B=Qx. If A is the matrix of T in the standard basis, what is [T]B?
QuizSame invariants, same class?
Identity I and shear S=[1011] have the same trace (2) and determinant (1). Are they similar?
NumericHow high is the gripper?
A planar arm has L1=2, L2=1.5, θ1=30° and θ2=45°, with Mi as in the text. Calculate the gripper's y coordinate in the base frame.
NumericThe obstacle from the robot's perspective
A mobile robot's world pose is [R0⊤t1], with R the 90° rotation and t=(2,1): it converts robot to world coordinates, pmundo=Rprobot+t. An obstacle is at (3,4) in world coordinates. What is its x coordinate in the robot frame?
ProofComposition is multiplication, with indices
Prove: If T:V→W and S:W→U are linear and B=(vj), C=(wk), D=(ui) are bases of V, W and U, then [S∘T]D←B=[S]D←C[T]C←B.
0
Write T=[T]C←B=(tkj) and S=[S]D←C=(sik), that is, T(vj)=∑ktkjwk and S(wk)=∑isikui.
Step 1 of 5. Where do you begin?
ProofTrace is basis-independent
Prove: For A∈Rm×n and B∈Rn×m, tr(AB)=tr(BA). Consequently, similar matrices have the same trace.
0
Recall (AB)ii=∑k=1naikbki, and that AB is m×m while BA is n×n.
Step 1 of 4. Write tr(AB) with indices.
QuizA commutator equal to identity?
Do real matrices A,B∈Rn×n, with n≥1, exist such that AB−BA=I?
NumericTranslation exponentiates the derivative
Let S:P3→P3 be the shift (Sp)(x)=p(x+1). Write its matrix in the monomial basis (1,x,x2,x3) and calculate the sum of all entries.
CodeThe matrix of a map in any basis
Implement matrix_in_basis(T, basis). T is a linear map from Rn to Rn supplied as a Python function (accepting and returning NumPy arrays of length n), and basis is a list of n linearly independent vectors in standard coordinates. Return the n×n matrix of T in that basis: column j contains coordinates of T(bj) in the basis. Tests use rotations, projections and polynomial differentiation, represented by monomial coefficients.
import numpy as np
def matrix_in_basis(T, basis):
# columna j del resultado: coordenadas de T(b_j) en la base (b_1, ..., b_n)
pass
Shift+Enter to run
Summary
Key idea
A matrix is a linear map written in specific bases: its columns are basis images. Changing basis changes the matrix, A↦P−1AP, but not the map; what survives the change (trace, determinant, eigenvalues) truly describes it, and choosing a good basis can make the matrix diagonal.
Linearity preserves linear combinations. A linear map is determined by, and can be freely chosen through, basis images; its matrix stores them in columns, and A∈Rm×n goes from Rn to Rm.
Composition is multiplication, right to left: in ABx, B acts first. Row-by-column multiplication ensures this, giving associativity and noncommutativity.
Invertible means bijective and, for square matrices, injective, surjective and having basis columns. (AB)−1=B−1A−1, and systems are solved by factorization, not inversion.
Change of basis: if P has the new basis as columns, x=P[x]B and [T]B=P−1AP. Trace is invariant because tr(AB)=tr(BA).
Affine is not linear, but becomes linear in homogeneous coordinates: x↦Ax+b is a matrix (m+1)×(n+1), composing poses multiplies matrices in SE(2) or SE(3), and a dense layer with bias is a matrix with one extra column.