Transformations and forms in MATLAB — theory for building matrices column by column, checking diagonalisations and plotting with plot, fill and quiver (and the sofa that would not fit through the door)

Before moving the living room sofa I wanted to know if it would fit through the door tilted, and I learnt that a transformation is easier to understand drawn than computed. I did the topic 5 calculation from AG on paper, a 2×22 \times 2 matrix times four corners, and it said yes. Pablo measured it with a tape measure and it was a no: I had multiplied the matrix by the corners in the wrong order. With one fill before and another after I would have seen it in a second.

This is block 3 of the MATLAB programming intensive course and it is about plots and about building and checking matrices with code: the matrix of a transformation built column by column with a function, a numerical check of whether a rule is linear, transforming every point of a shape at once, checking a diagonalisation with eig and its powers, classifying a quadratic form with a function that applies Sylvester’s criterion, and drawing it all with plot, fill, quiver, hold on and axis equal. The theory is in linear transformations and diagonalisation and in bilinear and quadratic forms; here we take it as read. If you are missing functions or loops, they are in blocks 1 and 2.

In a nutshell: in MATLAB, the matrix of a linear transformation is built by putting as its columns the images of the standard basis vectors, and with it you transform a whole shape by multiplying the matrix by the matrix of its vertices. The results are drawn with fill (polygons), plot (lines) and quiver (arrows), with hold on to overlay and axis equal so they are not distorted.

Before you start. For this block you only need to know how to write a function and a for loop in MATLAB (blocks 1 and 2) and, from the algebra, three things: multiplying a matrix by a vector, what an eigenvalue is and what a quadratic form is. That is all. The article has three parts, in this order: building the matrix of a rule and checking that the rule is linear; using that matrix on a whole shape, the sofa, and plotting it; and two checks from topics 5 and 6, diagonalisation with its powers and the classification of a quadratic form. If you get lost, go back to the sofa and the shear: almost the whole article asks them questions.

What you will program and for which topic

The example is the living room floor plan seen from above, in metres. The sofa is a 2 m by 0.9 m rectangle with a corner at the origin. In MATLAB a shape is stored as a matrix with one vertex per column: the first row is the xx values and the second, the yy values. So that the polygon closes when drawn, the first vertex is repeated at the end:

sofa = [0 2 2   0   0;      % x of the corners (and back to the first)
        0 0 0.9 0.9 0];     % y of the corners
size(sofa)

Output:

ans =

     2     5

Two rows and five columns: four corners and the repeated one. With that matrix we will program:

  • matrix_of: the matrix of a transformation from its rule, column by column (topic 5).
  • is_linear: a numerical check of whether a rule is linear (topic 5).
  • draw_grid: the plane’s grid deformed by a matrix (topic 5).
  • The check of a diagonalisation and of its powers (topic 5).
  • classify: the classification of a quadratic form by Sylvester’s criterion, compared with the eigenvalues (topic 6).

The plots in this article were drawn with the data the code computes. To see them yourself, run the blocks in the site’s MATLAB playground, which now draws plot, fill, quiver and plot3, or in your MATLAB or MATLAB Online (you get it free with your ULPGC account: the AG installation guide explains how).

Rules that are functions: anonymous functions

A transformation is a rule: a vector goes in and another comes out. For short rules, MATLAB has anonymous functions, written on one line and stored in a variable:

stretch = @(v) [1.5*v(1); v(2)];                 % 50 % longer in x
shear   = @(v) [v(1) + 0.5*v(2); v(2)];          % tilt to the right
mirror  = @(v) [v(2); v(1)];                     % reflection in the line y = x
turn30  = @(v) [cosd(30)*v(1) - sind(30)*v(2);   % 30 degree rotation
                sind(30)*v(1) + cosd(30)*v(2)];
move    = @(v) v + [1; 0];                       % translate one metre to the right
shear([2; 0.9])

Output:

ans =

    2.4500
    0.9000

@(v) says the function takes one thing and calls it v; what follows is what it returns. shear([2; 0.9]) applies the rule to the top right corner of the sofa: 2+0.5⋅0.9=2.452 + 0.5 \cdot 0.9 = 2.45. cosd and sind work in degrees, so you do not have to convert to radians.

An anonymous function “keeps” the value its variables had when it was created. If you write k = 2; f = @(v) k*v; and then change k = 5, f still multiplies by 2. If you want the new value, create f again.

The matrix of a transformation, column by column

Before the sentence from the topic, do it in your head. You have the shear rule, f(x,y)=(x+0.5y; y) f(x, y) = (x + 0.5y;\ y) , and you want a matrix C C that does the same: C C times any vector should give what the rule gives. Which numbers go inside?

The question is answered with two very specific vectors. If you multiply a matrix by (1,0) (1, 0) , what comes out is its first column, exactly as it is: the 1 picks the first column and the 0 switches off the second. And if you multiply it by (0,1) (0, 1) , out comes the second column. So there is nothing to guess: you only have to ask the rule what it does with those two vectors.

VectorWhat the shear givesWhy
(1,0) (1, 0) (1,0) (1, 0) x=1 x = 1 and y=0 y = 0 : 1+0.5⋅0=1 1 + 0.5 \cdot 0 = 1 , and y y is still 0
(0,1) (0, 1) (0.5; 1) (0.5;\ 1) x=0 x = 0 and y=1 y = 1 : 0+0.5⋅1=0.5 0 + 0.5 \cdot 1 = 0.5 , and y y is still 1

Those two answers, standing upright side by side, are the matrix: C=(10.501) C = \begin{pmatrix} 1 & 0.5 \\ 0 & 1 \end{pmatrix} . Check it with the sofa corner you already worked out: C⋅(2; 0.9)=(2+0.5⋅0.9; 0.9)=(2.45; 0.9) C \cdot (2;\ 0.9) = (2 + 0.5 \cdot 0.9;\ 0.9) = (2.45;\ 0.9) , the same as shear([2; 0.9]) gave.

And why are two vectors enough to know everything? Because any vector can be written with them: (2; 0.9)=2⋅(1,0)+0.9⋅(0,1) (2;\ 0.9) = 2 \cdot (1, 0) + 0.9 \cdot (0, 1) , and a linear rule respects sums and multiples, so its image is 2 times the image of (1,0) (1, 0) plus 0.9 times the image of (0,1) (0, 1) . Once you know what it does with those two, you know what it does with the whole plane.

Writing the images as rows instead of columns. With the shear you would get (100.51) \begin{pmatrix} 1 & 0 \\ 0.5 & 1 \end{pmatrix} , which takes the corner (2; 0.9) (2;\ 0.9) to (2; 1.9) (2;\ 1.9) : a shear upwards, not to the right. Each image stands upright, in its own column.

Now you can give it the official names: the two vectors are the standard basis, e1 \mathbf{e}_1 and e2 \mathbf{e}_2 , and what you have just done is the rule from the topic.

Topic 5 says the columns of the matrix are the images of the standard basis: column 1 is f(e1)f(\mathbf{e}_1), column 2 is f(e2)f(\mathbf{e}_2)… Programmed with a loop over the columns of the identity:

function A = matrix_of(f, n)
% MATRIX_OF  Matrix of a linear transformation from R^n to R^n.
%   A = matrix_of(f, n): column j is the image f(e_j) of the j-th standard vector.
I = eye(n);
A = zeros(n);                 % reserve the size before filling it in
for j = 1:n
    A(:, j) = f(I(:, j));     % image of e_j, in column j
end
end
The columns are the images of the basisOn the left, e1 and e2; on the right, their images by the shear, (1, 0) and (0.5, 1); below, the matrix C with those two vectors as its columns.e1 = (1, 0)e2 = (0, 1)canonical basisshearf(e1) = (1, 0)f(e2) = (0.5, 1)their imagesC = 100.51column 1 = f(e1), column 2 = f(e2)
matrix_of does exactly this in a loop: column j = f(j-th column of the identity).
C = matrix_of(shear, 2)
G = matrix_of(turn30, 2)
E = matrix_of(mirror, 2)

Output:

C =

    1.0000    0.5000
         0    1.0000

G =

    0.8660   -0.5000
    0.5000    0.8660

E =

     0     1
     1     0

The shear leaves e1=(1,0)\mathbf{e}_1 = (1, 0) where it was and takes e2=(0,1)\mathbf{e}_2 = (0, 1) to (0.5; 1)(0.5;\ 1): that is why its second column is (0.5; 1)(0.5;\ 1). The rotation has (cos⁡30∘,sin⁡30∘)=(0.8660; 0.5)(\cos 30^\circ, \sin 30^\circ) = (0.8660;\ 0.5) in its first column. And the mirror swaps the axes.

The loop in matrix_of asks those two questions for you, one per pass. With matrix_of(shear, 2):

StepjI(:, j)f(I(:, j))A afterwardsWhy
before the loop———(0000) \begin{pmatrix} 0 & 0 \\ 0 & 0 \end{pmatrix} zeros(n) reserves a 2×2 2 \times 2 matrix full of zeros
pass 11(1,0) (1, 0) (1,0) (1, 0) (1000) \begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix} the first column of eye(2) is e1 \mathbf{e}_1 ; its image is written into column 1
pass 22(0,1) (0, 1) (0.5; 1) (0.5;\ 1) (10.501) \begin{pmatrix} 1 & 0.5 \\ 0 & 1 \end{pmatrix} now e2 \mathbf{e}_2 ; A(:, 2) = … writes only column 2 and leaves column 1 as it was

Two passes because n is 2: one for each basis vector. In R3 \mathbb{R}^3 there would be three passes and three columns, without changing a single line of the function. That is why the rules are written with ;, standing upright: f has to return a column, because that is what gets stored in A(:, j).

Check you’ve got it: which matrix does matrix_of(stretch, 2) return?

(1.5001) \begin{pmatrix} 1.5 & 0 \\ 0 & 1 \end{pmatrix} . Step by step: in pass 1, stretch receives (1,0) (1, 0) and returns (1.5⋅1; 0)=(1.5; 0) (1.5 \cdot 1;\ 0) = (1.5;\ 0) , which goes into column 1. In pass 2 it receives (0,1) (0, 1) and returns (1.5⋅0; 1)=(0,1) (1.5 \cdot 0;\ 1) = (0, 1) : the second column stays as in the identity. It makes sense: stretching in x x only touches the first coordinate, so only the column that comes from e1 \mathbf{e}_1 changes. Applied to the sofa, the corner (2; 0.9) (2;\ 0.9) goes to (3; 0.9) (3;\ 0.9) : a sofa 3 m long.

Is it linear? A check with numbers

matrix_of works with any rule, including the ones that are not linear, and then the matrix it gives does not represent the rule. Before you trust it, check: a linear rule satisfies f(au+bv)=af(u)+bf(v)f(a\mathbf{u} + b\mathbf{v}) = a f(\mathbf{u}) + b f(\mathbf{v}) and takes 0\mathbf{0} to 0\mathbf{0}. With some test vectors:

function linear = is_linear(f, n, tol)
% IS_LINEAR  Checks with test vectors whether the rule f from R^n to R^n is linear.
%   It is not a proof: if it gives false, it certainly is not; if it gives true, it probably is.
if nargin < 3
    tol = 1e-10;
end
u = (1:n)';                 % any two test vectors
v = (n:-1:1)' - 2;
a = 2;  b = -0.5;
left_side = f(a*u + b*v);
right_side = a*f(u) + b*f(v);
linear = norm(left_side - right_side) < tol && norm(f(zeros(n, 1))) < tol;
end

With the rules from the start, and the matrix the translation would give if we did not check:

is_linear(shear, 2)
is_linear(turn30, 2)
is_linear(move, 2)
M = matrix_of(move, 2)

Output:

ans =

  logical

   1

ans =

  logical

   1

ans =

  logical

   0

M =

     2     1
     0     1

The translation is not linear: it takes the origin to (1,0)(1, 0). And look at what matrix_of would do if you did not check: it gives you a matrix, [2 1; 0 1], which has nothing to do with moving the sofa (applied to the origin, it leaves it at the origin). A function that does not complain is not a function that gets it right. The “probably” is meant seriously: two test vectors are not a proof; the proof is the one in topic 5.

It is worth looking inside to see why is_linear says no to the translation. With n = 2, the test vectors are u = (1:2)', that is u=(1,2) \mathbf{u} = (1, 2) , and v = (2:-1:1)' - 2, that is (2,1)−(2,2)=(0,−1) (2, 1) – (2, 2) = (0, -1) ; the numbers are a=2 a = 2 and b=−0.5 b = -0.5 . The function works out the two sides of the equality separately:

CalculationWith the shearWith moveWhy
au+bv a\mathbf{u} + b\mathbf{v} (2; 4.5) (2;\ 4.5) (2; 4.5) (2;\ 4.5) (2,4)+(0; 0.5) (2, 4) + (0;\ 0.5) : the mix does not depend on the rule yet
left side: f(au+bv) f(a\mathbf{u} + b\mathbf{v}) (4.25; 4.5) (4.25;\ 4.5) (3; 4.5) (3;\ 4.5) the rule is applied only once, to the mix
f(u) f(\mathbf{u}) and f(v) f(\mathbf{v}) (2,2) (2, 2) and (−0.5; −1) (-0.5;\ -1) (2,2) (2, 2) and (1,−1) (1, -1) the rule is applied to each vector separately
right side: af(u)+bf(v) a f(\mathbf{u}) + b f(\mathbf{v}) (4.25; 4.5) (4.25;\ 4.5) (3.5; 4.5) (3.5;\ 4.5) the images are mixed with the same a a and b b
norm(left_side - right_side)00.5the shear matches; move is off by half a metre in x x

Where does that half metre come from? On the left, the translation’s metre is added once. On the right it is added inside f(u) f(\mathbf{u}) and inside f(v) f(\mathbf{v}) , and then multiplied by a a and by b b : a+b=2−0.5=1.5 a + b = 2 – 0.5 = 1.5 times in total. Once against 1.5 times: half a metre of difference in x x . With any a a and b b that do not add up to 1 the same happens, and that is why no translation is linear. The second condition, norm(f(zeros(n, 1))) < tol, would have caught it too: move takes (0,0) (0, 0) to (1,0) (1, 0) , which has norm 1. With the real output:

move = @(v) v + [1; 0];
u = [1; 2]; v = [0; -1]; a = 2; b = -0.5;
left_side = move(a*u + b*v)
right_side = a*move(u) + b*move(v)

Output:

left_side =

    3.0000
    4.5000

right_side =

    3.5000
    4.5000

The y y matches and the x x does not: 3 against 3.5.

Transforming a whole shape at once

Since each column of sofa is a vertex, multiplying the matrix by the shape transforms every vertex at once:

A⋅(∣∣∣p1p2⋯p5∣∣∣)=(∣∣∣Ap1Ap2⋯Ap5∣∣∣) A \cdot \begin{pmatrix} | & | & & | \\ \mathbf{p}_1 & \mathbf{p}_2 & \cdots & \mathbf{p}_5 \\ | & | & & | \end{pmatrix} = \begin{pmatrix} | & | & & | \\ A\mathbf{p}_1 & A\mathbf{p}_2 & \cdots & A\mathbf{p}_5 \\ | & | & & | \end{pmatrix}
moved = C * sofa                  % every corner with the shear
with_loop = zeros(size(sofa));
for k = 1:size(sofa, 2)
    with_loop(:, k) = shear(sofa(:, k));   % one by one, with the rule
end
difference = norm(moved - with_loop)

Output:

moved =

         0    2.0000    2.4500    0.4500         0
         0         0    0.9000    0.9000         0

difference =

     0

The product C * sofa and the loop that applies the rule corner by corner give the same. This is called vectorising: writing the operation on the whole matrix instead of a loop. It is shorter, harder to get wrong and, with thousands of points, much faster.

Why it works: in the product C⋅ C \cdot sofa, column k k of the result only uses column k k of sofa. Each corner is multiplied by C C without noticing there are others, which is exactly what the loop does. Corner by corner:

ColumnCornerC C times the cornerWhy
1(0,0) (0, 0) (0,0) (0, 0) a matrix always leaves the origin where it is
2(2,0) (2, 0) (2,0) (2, 0) y=0 y = 0 : there is nothing to shift, the base of the sofa does not move
3(2; 0.9) (2;\ 0.9) (2.45; 0.9) (2.45;\ 0.9) 2+0.5⋅0.9=2.45 2 + 0.5 \cdot 0.9 = 2.45 : it shifts by half its height
4(0; 0.9) (0;\ 0.9) (0.45; 0.9) (0.45;\ 0.9) 0+0.5⋅0.9=0.45 0 + 0.5 \cdot 0.9 = 0.45 : the same shift, because it is at the same height
5(0,0) (0, 0) (0,0) (0, 0) the corner repeated to close the polygon; it comes out repeated too

The two top corners move by the same amount, 0.45 m, because they are at the same height, and the bottom ones do not move: that is a shear. And the fifth column comes out the same as the first without doing anything special, so the transformed polygon is still closed.

sofa * C. With the shape stored as rows of xx and of yy, the order is matrix times shape. sofa * C multiplies a 2×52 \times 5 matrix by a 2×22 \times 2 one and MATLAB gives a size error; if you had stored the vertices by rows (one vertex per row), there would be no error, but it would compute something else. That was my mistake with the door.

Plotting: plot, fill, quiver, hold on and axis equal

Five commands are enough for almost everything you need in AG:

CommandWhat it drawsExample
plot(x, y, 'r--')A line through the points, with a style'r--': red and dashed; 'ko': black dots
fill(x, y, 'b')A filled polygonfill(sofa(1,:), sofa(2,:), 'b')
quiver(x, y, u, v, 0)Arrows from (x,y)(x, y) with components (u,v)(u, v)The 0 means “no rescaling”
hold onThe next thing is drawn on topWithout it, each command erases the previous one
axis equalThe same scale on both axesWithout it, a square comes out as a rectangle

And to finish a plot: title, xlabel, ylabel, legend (one text per thing drawn, in the same order) and grid on. The sofa before and after the shear, with the columns of the matrix as arrows:

figure
fill(sofa(1,:), sofa(2,:), 'b', 'FaceAlpha', 0.3)     % before
hold on
fill(moved(1,:), moved(2,:), 'r', 'FaceAlpha', 0.3)   % after
quiver([0 0], [0 0], C(1,:), C(2,:), 0, 'k')          % the columns of C
axis equal
grid on
legend('before', 'after', 'columns of C')
title('The sofa with the shear')
xlabel('x (m)'), ylabel('y (m)')
The sofa with the shearMATLAB plot: the sofa rectangle, 2 by 0.9 metres, in blue, and the parallelogram produced by the shear, in red, with its top moved 0.45 metres; two black arrows from the origin to (1, 0) and (0.5, 1).00.511.522.500.250.50.751The sofa with the shearx (m)y (m)beforeaftercolumns of C
The sofa before (blue) and after (red) the shear, with the columns of C as arrows.

The plot shows what the numbers say: the base of the sofa does not move (the first column of C is e1\mathbf{e}_1) and the top is shifted 0.45 m, half its height. The area does not change: det⁡C=1\det C = 1, and the red parallelogram has the same base and the same height as the blue rectangle.

quiver([0 0], [0 0], C(1,:), C(2,:), 0, 'k') deserves a slow reading. It draws two arrows (because the vectors have two elements), both from (0,0)(0, 0). The first has components C(1,1) and C(2,1), that is, the first column; the second, the second column. That is how you see that the columns of the matrix are the images of the basis.

The deformed grid, with a function that draws

What a matrix does to the whole plane is seen by deforming a grid. A function that returns nothing, it only draws:

function draw_grid(A, side)
% DRAW_GRID  Draws the grid from -side to side and its image under the matrix A.
if nargin < 2
    side = 2;
end
t = linspace(-side, side, 2);           % the two ends of each line
hold on
for k = -side:side
    vertical = [k k; t];                % the line x = k, by its two ends
    horizontal = [t; k k];              % the line y = k
    plot(vertical(1,:), vertical(2,:), 'k:')        % original, dotted
    plot(horizontal(1,:), horizontal(2,:), 'k:')
    v2 = A * vertical;  h2 = A * horizontal;          % the same ones, transformed
    plot(v2(1,:), v2(2,:), 'b')
    plot(h2(1,:), h2(2,:), 'r')
end
axis equal
grid on
end

[k k; t] is a 2×22 \times 2 matrix with the two ends of the vertical segment x=kx = k: (k,−2)(k, -2) and (k,2)(k, 2). Since a matrix takes lines to lines, transforming the two ends is enough. With the 30° rotation:

figure
draw_grid(G)
title('The 30 degree rotation deforms the grid')
The 30 degree rotation deforms the gridMATLAB plot: a grid from -2 to 2 in dotted lines and the same grid rotated 30 degrees, with the rotated vertical lines in blue and the horizontal ones in red.−4−2024−202The 30 degree rotation deforms the grid
The original dotted grid and the one rotated 30 degrees (blue the vertical lines, red the horizontal ones): they still form squares.

The blue lines are the rotated vertical ones and the red ones, the horizontal ones. They still form squares of the same size: a rotation does not deform, it only turns (which is why det⁡G=1\det G = 1 and its columns are orthonormal).

With the shear the grid no longer forms squares, and it is worth guessing the picture before asking MATLAB for it.

Check you’ve got it: what does draw_grid(C) draw with the shear?

The red lines stay horizontal and the blue ones lean to the right; the squares become parallelograms with the same area. Step by step: a horizontal line y=k y = k has the points (t,k) (t, k) , and the shear takes them to (t+0.5k; k) (t + 0.5k;\ k) . The y y is still k k , so the segment stays on the same line and only slides 0.5k 0.5k along it. A vertical line x=k x = k has the points (k,t) (k, t) , which go to (k+0.5t; t) (k + 0.5t;\ t) : every time t t goes up by 1, x x moves forward 0.5, so the line leans. The vertical line x=0 x = 0 , for example, now goes from (−1,−2) (-1, -2) to (1,2) (1, 2) . And since det⁡C=1 \det C = 1 , each parallelogram has the same area as the square it comes from, just as with the sofa.

Checking a diagonalisation and its powers

Topic 5 diagonalises by hand. In MATLAB, [P, D] = eig(A) returns the eigenvectors in the columns of P and the eigenvalues on the diagonal of D. The check is the definition: AP=PDAP = PD.

Take the matrix that stretches the plane along the diagonal, like a rug that gives when you step on it:

A=(2112) A = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}

Before asking eig, do it in your head. An eigenvector is a direction the matrix does not bend: the arrow comes out longer or shorter, but pointing the same way. Try three arrows:

VectorA A times the vectorSame direction?Why
(1,0) (1, 0) (2,1) (2, 1) noout comes the first column of A A , which bends upwards
(1,1) (1, 1) (3,3) (3, 3) yes, by 32+1=3 2 + 1 = 3 in each coordinate: the same arrow, three times longer
(−1,1) (-1, 1) (−1,1) (-1, 1) yes, by 1−2+1=−1 -2 + 1 = -1 and −1+2=1 -1 + 2 = 1 : the same arrow comes out, unchanged

You already have the diagonalisation without doing any of the topic’s calculations: two directions that do not bend, (1,1) (1, 1) with eigenvalue 3 and (−1,1) (-1, 1) with eigenvalue 1. That is the rug: along the diagonal y=x y = x it gives up to three times its length, and in the perpendicular direction it stays as it was. What eig is about to return are these same two directions, written another way. Now, with MATLAB:

A = [2 1; 1 2];
[P, D] = eig(A)
check = norm(A*P - P*D)

Output:

P =

   -0.7071    0.7071
    0.7071    0.7071

D =

     1     0
     0     3

check =

     0

Eigenvalues 1 and 3. The second column of P, (0.7071; 0.7071)(0.7071;\ 0.7071), is the direction y=xy = x, which is stretched by 3; the first, (−0.7071; 0.7071)(-0.7071;\ 0.7071), is the perpendicular one, which stays the same. eig gives them normalised (with norm 1); by hand you would have written (1,1)(1, 1) and (−1,1)(-1, 1), which are the same eigenvectors with another length.

The payoff of topic 5 is powers: Ak=PDkP−1A^k = P D^k P^{-1}, and DkD^k is raising the diagonal. Programmed as a function with its check that the matrix is diagonalisable:

function Ak = diag_power(A, k)
% DIAG_POWER  A^k by diagonalising: P * D^k * inv(P).
%   Gives an error if A is not diagonalisable (the eigenvectors do not form a basis).
[P, D] = eig(A);
if rank(P) < size(A, 1)
    error('diag_power:notDiag', 'The matrix is not diagonalisable: rank of P = %d.', rank(P));
end
Ak = P * diag(diag(D).^k) / P;    % / P means multiplying by the inverse of P
end

The tenth power, compared with the one MATLAB computes directly:

A10 = diag_power(A, 10)
difference = norm(A10 - A^10) / norm(A^10)

Output:

A10 =

   1.0e+04 *

    2.9525    2.9524
    2.9524    2.9525

difference =

   6.1609e-17

Checking one entry by hand: A10=PD10P−1A^{10} = P D^{10} P^{-1} gives 310+12=59049+12=29525\tfrac{3^{10} + 1}{2} = \tfrac{59049 + 1}{2} = 29525 on the diagonal. The difference from A^10 is measured relatively (divided by the norm of the result), because with five-digit numbers an absolute error of 10−1110^{-11} is as small as one of 10−1610^{-16} with one-digit numbers.

The formula Ak=PDkP−1 A^k = P D^k P^{-1} looks like magic, but in words it is simple: switch to the directions that do not bend, multiply there (which is easy) and come back. With the first column of A10 A^{10} , which is what A10 A^{10} does to e1=(1,0) \mathbf{e}_1 = (1, 0) , and with the hand-written eigenvectors, (1,1) (1, 1) and (−1,1) (-1, 1) :

StepCalculationWhy
1. Write e1 \mathbf{e}_1 with the eigenvectors(1,0)=12(1,1)−12(−1,1) (1, 0) = \tfrac{1}{2}(1, 1) – \tfrac{1}{2}(-1, 1) this is what P−1 P^{-1} does: it gives the coordinates in the eigenvector basis
2. Apply A A ten times to each piece(1,1) (1, 1) becomes 310(1,1) 3^{10}(1, 1) and (−1,1) (-1, 1) stays the samein those directions A A only multiplies, by 3 and by 1: that is raising the diagonal, D10 D^{10}
3. Put it back together590492(1,1)−12(−1,1) \tfrac{59049}{2}(1, 1) – \tfrac{1}{2}(-1, 1) this is what P P does: it rebuilds the vector from the pieces already multiplied
4. Result(29525,29524) (29525, 29524) 59049+12 \tfrac{59049 + 1}{2} and 59049−12 \tfrac{59049 – 1}{2} : the first column of the output

Ten matrix products have turned into raising two numbers, 3 and 1, to the tenth power. With k=100 k = 100 it would cost the same, and that is why topic 5 insists so much on diagonalising.

Check you’ve got it: what is the third power of A, without multiplying matrices?

A3=(14131314) A^3 = \begin{pmatrix} 14 & 13 \\ 13 & 14 \end{pmatrix} . Step by step: the same three steps with 33=27 3^3 = 27 instead of 310 3^{10} . The first column is 272(1,1)−12(−1,1)=(14,13) \tfrac{27}{2}(1, 1) – \tfrac{1}{2}(-1, 1) = (14, 13) . The second comes from e2=(0,1)=12(1,1)+12(−1,1) \mathbf{e}_2 = (0, 1) = \tfrac{1}{2}(1, 1) + \tfrac{1}{2}(-1, 1) , so it is 272(1,1)+12(−1,1)=(13,14) \tfrac{27}{2}(1, 1) + \tfrac{1}{2}(-1, 1) = (13, 14) . To check it by hand: A2=(5445) A^2 = \begin{pmatrix} 5 & 4 \\ 4 & 5 \end{pmatrix} , and the first entry of A2A A^2 A is 5⋅2+4⋅1=14 5 \cdot 2 + 4 \cdot 1 = 14 .

Three details of the code:

  • diag(D) pulls out the diagonal as a vector; .^k raises each element; and diag(...) turns them back into a diagonal matrix. Raising D^k also works, but this way it is clear that only numbers are raised.
  • X / P is XP−1X P^{-1}, just as A\b is A−1bA^{-1}\mathbf{b}. It is more accurate than X * inv(P).
  • The check rank(P) < n is the topic’s: if there are not nn independent eigenvectors, you cannot diagonalise. The shear is the classic example:
diag_power(C, 10)

Output:

The matrix is not diagonalisable: rank of P = 1.

eig(C) returns the eigenvalue 1 twice, but its two “eigenvectors” are practically the same (MATLAB gives them almost equal, separated by a rounding error), so rank(P) is 1 and the function refuses. Checking before computing avoids returning a meaningless matrix.

Classifying a quadratic form with a function

Sylvester’s criterion from topic 6 looks at the leading principal minors of the symmetric matrix, Δ1,Δ2,…\Delta_1, \Delta_2, \ldots (the determinants of the top left corners): all positive, positive definite; alternating starting with negative, negative definite. If a minor is 0, Sylvester does not decide, and you have to look at the eigenvalues. Programmed with a loop and a chained if:

function kind = classify(A, tol)
% CLASSIFY  Classifies the quadratic form with symmetric matrix A using Sylvester's criterion.
if nargin < 2
    tol = 1e-10;
end
if norm(A - A') > tol
    error('classify:notSymmetric', 'The matrix of a quadratic form must be symmetric.');
end
n = size(A, 1);
minors = zeros(1, n);
for k = 1:n
    minors(k) = det(A(1:k, 1:k));         % the leading principal minor of order k
end
if all(minors > tol)
    kind = 'positive definite';
elseif all(minors(1:2:end) < -tol) && all(minors(2:2:end) > tol)
    kind = 'negative definite';           % odd ones negative, even ones positive
elseif any(abs(minors) <= tol)
    kind = 'Sylvester undecided';         % there is a zero minor
else
    kind = 'indefinite';
end
end

minors(1:2:end) are the odd-order ones (1, 3, 5…) and minors(2:2:end), the even-order ones. And the tolerance shows up again: a determinant that should be 0 can come out as 10−1710^{-17}.

To compare, the classification by the signs of the eigenvalues, which always decides:

function kind = classify_eig(A, tol)
% CLASSIFY_EIG  Classifies the quadratic form of A by the signs of its eigenvalues.
if nargin < 2
    tol = 1e-10;
end
l = eig(A);
if all(l > tol),               kind = 'positive definite';
elseif all(l < -tol),          kind = 'negative definite';
elseif all(l > -tol),          kind = 'positive semidefinite';
elseif all(l < tol),           kind = 'negative semidefinite';
else,                          kind = 'indefinite';
end
end

Four forms, one of each kind, with both functions:

forms = {[2 1; 1 2], [-3 1; 1 -2], [1 2; 2 1], [1 1; 1 1]};
for k = 1:numel(forms)
    F = forms{k};
    fprintf('%-20s %-22s %s\n', mat2str(F), classify(F), classify_eig(F));
end

Output:

[2 1;1 2]            positive definite      positive definite
[-3 1;1 -2]          negative definite      negative definite
[1 2;2 1]            indefinite             indefinite
[1 1;1 1]            Sylvester undecided    positive semidefinite

forms is a cell array ({}), which stores matrices of any size in a list; forms{k} pulls out the kk-th. %-20s in fprintf writes a text taking up 20 characters, aligned to the left: that is how the columns come out. The first three agree; in the fourth, Δ1=1\Delta_1 = 1 and Δ2=0\Delta_2 = 0, Sylvester does not decide and the eigenvalues (0 and 2) say positive semidefinite. Checking the third by hand: Δ1=1>0\Delta_1 = 1 > 0 and Δ2=1−4=−3<0\Delta_2 = 1 – 4 = -3 < 0, indefinite.

In words, before the minors: a form is positive definite if it gives a positive number for every vector other than zero, negative definite if it always gives a negative one, and indefinite if it gives both signs. Sylvester is a shortcut for finding out without trying vectors. And the chained if in classify is read from top to bottom and stops at the first question whose answer is yes. With the two least obvious forms on the list:

FormminorsQuestionAnswerWhy
[-3 1; 1 -2](−3,5) (-3, 5) all positive?noΔ1=−3 \Delta_1 = -3 is already negative
[-3 1; 1 -2](−3,5) (-3, 5) odd ones negative and even ones positive?yes: negative definiteΔ1=−3<0 \Delta_1 = -3 < 0 and Δ2=6−1=5>0 \Delta_2 = 6 – 1 = 5 > 0 ; the remaining questions are not asked
[1 1; 1 1](1,0) (1, 0) all positive?noΔ2=1−1=0 \Delta_2 = 1 – 1 = 0 is not greater than tol
[1 1; 1 1](1,0) (1, 0) odd ones negative and even ones positive?noΔ1=1 \Delta_1 = 1 is not negative
[1 1; 1 1](1,0) (1, 0) any zero minor?yes: Sylvester does not decideΔ2=0 \Delta_2 = 0 is within the tolerance

The order of the questions matters. The zero-minor one comes after the two “definite” ones and before “indefinite”: with a zero minor, the criterion as stated in the topic gives no answer, so the function does not risk saying “indefinite” and leaves the last word to the eigenvalues. For [1 1; 1 1] they are 0 and 2, neither negative: positive semidefinite.

Check you’ve got it: what do classify and classify_eig return for [-1 -1; -1 -1], the fourth form with its sign changed?

classify says “Sylvester does not decide” and classify_eig, “negative semidefinite”. Step by step: the minors are Δ1=−1 \Delta_1 = -1 and Δ2=(−1)(−1)−(−1)(−1)=0 \Delta_2 = (-1)(-1) – (-1)(-1) = 0 . All positive? No. Odd ones negative and even ones positive? Δ1=−1 \Delta_1 = -1 is negative, but Δ2=0 \Delta_2 = 0 is not positive: no. Any zero minor? Yes, Δ2 \Delta_2 : Sylvester does not decide. The eigenvalues are those of [1 1; 1 1] with the sign changed, 0 and −2 -2 . All greater than tol? No. All less than -tol? No, 0 is not. All greater than -tol? No, because of the −2 -2 . All less than tol? Yes: negative semidefinite. Changing the sign of the matrix changes the sign of the form, and what was positive becomes negative.

When you have two functions that should give the same thing, a table with both columns in a loop (like this one) finds the odd cases straight away. It is the home-made version of automated tests.

Common mistakes (with MATLAB’s real message)

1. Shape times matrix instead of matrix times shape.

sofa * C

Output:

Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise multiplication.

2. A rule of another dimension. If the rule uses three coordinates and you ask for the 2×22 \times 2 matrix:

turn_z = @(v) [-v(2); v(1); v(3)];      % a rotation in R^3, about the z axis
matrix_of(turn_z, 2)

Output:

Index exceeds the number of array elements. Index must not exceed 2.

Inside matrix_of, f(I(:, j)) receives two-element vectors and the rule asks for v(3). The error appears inside the anonymous function, far from where the real mistake is (the 2 in the call): matrix_of(turn_z, 3) works.

3. Classifying a matrix that is not symmetric. The function defends itself:

classify([1 4; 0 1])

Output:

The matrix of a quadratic form must be symmetric.

The form x2+4xy+y2x^2 + 4xy + y^2 is written with the symmetric matrix [1 2; 2 1]: the 4 is shared between the two off-diagonal entries.

  • Forgetting hold on. Each fill or plot erases the previous one and you only see the last.
  • Forgetting axis equal. The 30° rotation looks like a shear and squares come out as rectangles.
  • An open polygon. If you do not repeat the first vertex at the end, plot does not close the shape (fill does close it).
  • legend with too few texts or in another order. The legend assigns the texts in drawing order.

Try it in the MATLAB playground

In the site’s MATLAB playground you can try the matrix part and the plots too. This script builds the matrix of a rule, transforms the sofa and classifies a form:

% The living room sofa: matrix of a rule and its effect on the corners
sofa = [0 2 2 0 0; 0 0 0.9 0.9 0];
rule = @(v) [v(1) + 0.5*v(2); v(2)];      % the shear
A = matrix_of(rule, 2)
moved = A * sofa
area_before_after = [2*0.9, abs(det(A))*2*0.9]
[P, D] = eig([2 1; 1 2])

function A = matrix_of(f, n)
I = eye(n);  A = zeros(n);
for j = 1:n
    A(:, j) = f(I(:, j));
end
end

Things to look at:

  1. Change the rule to the mirror one, @(v) [v(2); v(1)], and look at the sign of det(A): a reflection flips the shape over.
  2. Put in the move rule, @(v) v + [1; 0], and compare A*sofa with what you expected: the matrix does not represent a translation.
  3. Check A*P - P*D with the matrix [2 1; 1 2] and then with [1 0.5; 0 1].
  4. Add the sofa block with fill, hold on and quiver at the end and watch the before and after being drawn.

And to move the matrix yourself and watch the grid deform live, with its eigenvectors, there is the Plane transformations simulator.

Summary

PieceWhat forExample
Anonymous functionA short rule in a variableshear = @(v) [v(1) + 0.5*v(2); v(2)]
Matrix by columnsColumn j is f(e_j)A(:, j) = f(I(:, j))
Checking linearityBefore trusting the matrixnorm(f(a*u + b*v) - (a*f(u) + b*f(v)))
Shape as a matrixOne vertex per columnmoved = A * sofa
fill, plot, quiverPolygons, lines, arrowsquiver(0, 0, u, v, 0)
hold on, axis equalOverlay, same scaleAlways in geometry
[P, D] = eig(A)Diagonalise and checknorm(A*P - P*D)
CellsA list of matricesforms{k}

Three ideas to take away:

  1. The columns of the matrix are the images of the basis. With that sentence you build any matrix with a loop, and with quiver you see it.
  2. A shape is a matrix of vertices, and transforming it is a multiplication. Matrix times shape, never the other way round.
  3. Every calculation in the topic has its one-line check: is_linear, norm(A*P - P*D), the power against A^k and Sylvester against eig.

Now it is your turn: in the block 3 exercises of the intensive course you will program the kernel and the image, the change of basis of a transformation and the diagonalisation of a quadratic form, and you will plot their results, with commented solutions, “What is wrong here?” and a cheat sheet.

Did this article help you? Here is how you can support SergioLearns →

Next step: exercisesTransformations and forms in MATLAB — exercises to build matrices column by column, draw a distorted sticker and classify forms with Sylvester (and the transpose from lab assignment 4)Cheat sheet: the block on one page, to reviewCheat sheetLab assignments: the block's functions and a model scriptFor your lab assignments