Complex numbers and geometry in MATLAB — theory for rotating with exp(1i*θ), programming nth roots and measuring distances with functions (and the robot vacuum that always turned left)

The flat’s robot vacuum taught me that rotating is multiplying by a complex number: every time it bumps into something, it turns 90 degrees and carries on straight. I wanted to simulate its route in MATLAB for AG topic 7 with sines, cosines and a rotation matrix at every step, and I got a crooked square because I mixed degrees and radians on the third turn. With the position as a complex number and the turn as 1i, the loop has three lines and there are no angles to mix up.

This is block 4, the last one of the MATLAB programming intensive course, and it brings the last two AG topics together with code: complex numbers in MATLAB (1i, abs, angle, exp(1i*θ) and how to plot them), a function that computes and plots the nth roots and is compared with roots, and the geometry of affine space as functions: the distance from a point to a line and to a plane, and the relative position of two lines decided with rank. We finish with plot3. The theory is in complex numbers and in affine space; here we take it as read. Functions, loops and plots come from blocks 1, 2 and 3.

In a nutshell: in MATLAB, a complex number is written with 1i (for example z = 3 + 2i), and abs(z) and angle(z) give its modulus and its argument in radians. Multiplying by exp(1i*θ) rotates a point by an angle θ about the origin, and plot(z) with a vector of complex numbers plots the real part against the imaginary part.

Before you start. For this block all you need is to know how to write a function and a for loop in MATLAB (blocks 1 to 3) and, from topics 7 and 8, that a complex number x+yi x + yi is a point in the plane with a modulus and an argument, and what the dot product is. Nothing else. The article has two parts: complex numbers as points that move (the robot that turns, the chair around the table and the corners of the rug, which are roots); and the geometry of space as functions (the lamp and the ceiling, the robot and the wall, the rail, the beam and the cable). If you get lost, go back to the living room: the whole article keeps asking it questions.

What you will program and for which topic

The example is the flat’s living room, seen from above, with the origin at a corner and distances in metres. A point on the floor, (x,y)(x, y), can be stored as the complex number x+yix + yi, and then adding is moving and multiplying by a complex number of modulus 1 is rotating. For the ceiling, which in the flat slopes under the roof, we will jump to three dimensions. We will program:

  • the robot vacuum’s route with a loop of complex numbers, and its plot (topic 7);
  • turn, which rotates a point about any center (topic 7);
  • nth_roots, which gives the nn roots of a complex number and, if you do not ask for an output, plots them (topic 7);
  • dist_point_line, dist_point_plane and line_position, with their checks (topic 8);
  • and the sloping ceiling with the lamp, in plot3 (topic 8).

Before the code: why multiplying by i rotates

Before writing a single line of MATLAB, do it in your head. The robot is at (3,2) (3, 2) , the complex number 3+2i 3 + 2i . What happens if you multiply it by i i ?

(3+2i)⋅i=3i+2i2 (3 + 2i) \cdot i = 3i + 2i^2 , and since i2=−1 i^2 = -1 , you get −2+3i -2 + 3i . The point (3,2) (3, 2) has moved to (−2,3) (-2, 3) : draw it and you will see the same point turned a quarter turn to the left, about the corner.

Coincidence? Repeat the calculation with letters: (x+yi)⋅i=−y+xi (x + yi) \cdot i = -y + xi . The point (x,y) (x, y) always goes to (−y,x) (-y, x) , which is the rule for a 90° rotation. And the distance to the corner does not change (both are at 13 \sqrt{13} ); what changes is the angle, from 33.69° to 123.69°: 90° more.

That idea works for any complex number: when you multiply, the moduli multiply and the arguments add. i i has modulus 1 (it does not stretch) and argument 90° (it turns 90°); eiθ e^{i\theta} has modulus 1 and argument θ \theta : it turns θ \theta . Now you can give it its MATLAB names: 3 + 2i, abs, angle and exp(1i*θ).

Check you’ve got it: where does the robot go if you multiply 3 + 2i by -1i?

To 2−3i 2 – 3i , the point (2,−3) (2, -3) . Step by step: (3+2i)⋅(−i)=−3i−2i2=2−3i (3 + 2i) \cdot (-i) = -3i – 2i^2 = 2 – 3i . The modulus of −i -i is 1, so the distance is still 13 \sqrt{13} ; its argument is −90∘ -90^\circ , so the angle drops from 33.69° to −56.31∘ -56.31^\circ . Multiplying by i i turns left; by −i -i , right.

Complex numbers in MATLAB: just enough to program

z = 3 + 2i                 % the robot, 3 m from one wall and 2 m from the other
modulus = abs(z)           % distance to the corner
argument = angle(z)        % angle with the x axis, in radians
degrees = rad2deg(argument)
conj(z)                    % the reflection in the x axis

Output:

z =

   3.0000 + 2.0000i

modulus =

    3.6056

argument =

    0.5880

degrees =

   33.6901

ans =

   3.0000 - 2.0000i

Calculations by hand: ∣z∣=32+22=13=3.6056|z| = \sqrt{3^2 + 2^2} = \sqrt{13} = 3.6056 and arg⁡z=arctan⁡(2/3)=33.69∘\arg z = \arctan(2/3) = 33.69^\circ. angle returns radians, between −π-\pi and π\pi, and it also looks at the quadrant (unlike atan(b/a)); rad2deg and deg2rad convert between the two without you having to remember 180/π180/\pi.

Three things worth knowing before you program:

  • Write 1i, not i. i and j are −1\sqrt{-1} only as long as you do not use them as variables. After a for i = 1:3, 2 + 3*i gives 11. 3i or 3 + 2i (a number stuck to the i) are always complex, but 1i on its own is the safe form.
  • The apostrophe conjugates. With complex numbers, v' transposes and conjugates; to transpose without conjugating you use v.'. With real numbers it makes no difference; with complex numbers it is a typical mistake.
  • exp(1i*t) is the point with modulus 1 and angle t. Multiplying by it rotates by t radians about the origin.
turn90 = exp(1i*pi/2)          % almost 1i: the computer's cos(pi/2) is not exactly 0
z * 1i                         % z rotated 90 degrees
v = [1+1i; 2-1i];
v'                             % conjugate transpose
v.'                            % transpose only

Output:

turn90 =

   0.0000 + 1.0000i

ans =

  -2.0000 + 3.0000i

ans =

   1.0000 - 1.0000i   2.0000 + 1.0000i

ans =

   1.0000 + 1.0000i   2.0000 - 1.0000i

exp(1i*pi/2) comes out as 0.0000+1.0000i0.0000 + 1.0000i: the real part is not exactly 0 (it is of the order of 10−1710^{-17}, because of the rounding of π\pi), but it is shown with four decimals. That is why, for the robot’s 90° turns, 1i is better than exp(1i*pi/2): it is exact. And z * 1i takes (3,2)(3, 2) to (−2,3)(-2, 3), the rotation from topic 7.

The robot program: a loop of complex numbers

The robot leaves the corner heading east (direction 11), moves forward, bumps into something, turns 90 degrees to the left (multiplies its direction by ii) and carries on. The version with complex numbers:

pos = 0;                   % it leaves the corner
heading = 1;               % facing east
route = pos;               % each stop gets noted here
legs = [4 3 4 3];          % metres to each bump: the room is 4 x 3
for k = 1:numel(legs)
    pos = pos + legs(k) * heading;   % move forward in its direction
    route(end+1) = pos;
    heading = heading * 1i;            % turn 90 degrees to the left
end
route

Output:

route =

   0.0000 + 0.0000i   4.0000 + 0.0000i   4.0000 + 3.0000i   0.0000 + 3.0000i   0.0000 + 0.0000i

Five stops and back to the corner: 0→4→4+3i→3i→00 \to 4 \to 4 + 3i \to 3i \to 0. The direction goes through 1,i,−1,−i1, i, -1, -i and back to 11, because i4=1i^4 = 1. The trace table, pass by pass:

Passlegs(k)heading beforepos afterheading after
141144ii
23ii4+3i4 + 3i−1-1
34−1-13i3i−i-i
43−i-i0011

With sines and cosines you would need to carry an angle, add 90 on each pass and compute two coordinates; here the direction is a number and turning is a multiplication.

The trace, with the reason for each pass

On each pass two things happen, always in this order: the robot moves forward (pos adds the leg times the direction) and then it turns (heading is multiplied by i i ).

PassposheadingWhy
10+4⋅1=4 0 + 4 \cdot 1 = 4 1⋅i=i 1 \cdot i = i facing east: 4 m along the bottom wall; it bumps and turns north
24+3⋅i=4+3i 4 + 3 \cdot i = 4 + 3i i⋅i=−1 i \cdot i = -1 3 m upwards; i2=−1 i^2 = -1 means facing west
34+3i−4=3i 4 + 3i – 4 = 3i −1⋅i=−i -1 \cdot i = -i 4 m to the left, x x goes back to 0; now it faces south
43i−3i=0 3i – 3i = 0 −i⋅i=1 -i \cdot i = 1 3 m down, to the corner, facing east again

heading always has modulus 1, because multiplying by i i does not stretch: the size of the step comes from the leg and the direction from heading.

Turning before moving. If you swap the two lines, the first leg already goes north: 0→4i→−3+4i→−3→0 0 \to 4i \to -3 + 4i \to -3 \to 0 , a rectangle 3 m wide and 4 m tall outside the room. The order of the lines is the order of what the robot does.

Plotting complex numbers with plot

plot with a single vector of complex numbers puts the real part on the xx axis and the imaginary part on the yy axis. So the route is a line:

figure
plot(route, 'o-')
axis equal
grid on
title('The robot''s route round the living room')
xlabel('x (m)'), ylabel('y (m)')
The robot's route round the living roomMATLAB plot: a rectangle with vertices at 0, 4, 4 + 3i and 3i, with circles at each stop.0240123The robot's route round the living roomx (m)y (m)
The robot's five stops: it leaves the corner, goes round the 4 by 3 metre room turning left and comes back.

The 4 m by 3 m rectangle of the living room, travelled anticlockwise: turning left is multiplying by ii, and ii rotates in that direction. (Inside a MATLAB text, an apostrophe is written twice: 'robot''s'.)

plot(real(route), imag(route)) and plot(route) do the same, but plot(x, route) with two arguments, the second one complex, ignores the imaginary part and warns you. If your data is complex, pass it on its own.

Rotating about any point: a function

z * exp(1i*t) rotates about the origin. To rotate about another point cc (the robot turning on the spot, or a chair round the table), you take cc to the origin, rotate and bring it back: c+(z−c) eitc + (z – c)\,e^{it}.

function w = turn(z, degrees, center)
% TURN  Rotates the points z (complex) by an angle in degrees about center (0 by default).
if nargin < 3
    center = 0;
end
w = center + (z - center) .* exp(1i * deg2rad(degrees));
end

One rotation about the origin and another about the table:

turn(3 + 2i, 90)                   % the same as (3 + 2i)*1i
chair = [1+1i, 1.5+1i, 1.5+1.5i, 1+1.5i];
turn(chair, 90, 2 + 2i)            % the chair, about the center of the table

Output:

ans =

  -2.0000 + 3.0000i

ans =

   3.0000 + 1.0000i   3.0000 + 1.5000i   2.5000 + 1.5000i   2.5000 + 1.0000i

The first matches z * 1i (apart from the rounding of exp, invisible with four decimals). The second rotates the four legs of a chair at once: turn works with vectors because it uses .*. Checking the first leg by hand: 1+i−(2+2i)=−1−i1 + i – (2 + 2i) = -1 – i; times ii, 1−i1 – i; plus 2+2i2 + 2i, 3+i3 + i.

The same calculation for the first leg, uncompressed. c+(z−c) eit c + (z – c)\,e^{it} is three steps:

StepCalculationWhy
Subtract the center(1+i)−(2+2i)=−1−i (1 + i) – (2 + 2i) = -1 – i the table becomes the origin
Turn(−1−i)⋅i=1−i (-1 – i) \cdot i = 1 – i multiplying can only turn about the origin, which is now the table
Add the center(1−i)+(2+2i)=3+i (1 – i) + (2 + 2i) = 3 + i it undoes the first step: the table goes back to its place

Turning without subtracting the center, c+z eit c + z\,e^{it} . With the first leg it gives (1+i)⋅i+(2+2i)=1+3i (1 + i) \cdot i + (2 + 2i) = 1 + 3i : the leg ends up 2 m from the table instead of staying at the same distance. One check always catches it: abs(w - center) has to be the same as abs(z - center).

Check you’ve got it: where does the chair leg 1.5 + 1.5i end up?

At 2.5+1.5i 2.5 + 1.5i , the third one in the output. Step by step: subtract the center, −0.5−0.5i -0.5 – 0.5i ; turn, (−0.5−0.5i)⋅i=0.5−0.5i (-0.5 – 0.5i) \cdot i = 0.5 – 0.5i ; add the center, 2.5+1.5i 2.5 + 1.5i . It was the leg closest to the table and it still is: a rotation does not change distances.

deg2rad(degrees) inside the function lets whoever uses it think in degrees, as in the living room, while the sums are done in radians, as exp wants. Hiding a conversion inside a function is the best way not to forget it.

nth roots, programmed and plotted

The living room rug is a hexagon, and its six corners are the sixth roots of 8: topic 7 says the nn roots of w=Rαw = R_\alpha have modulus Rn\sqrt[n]{R} and arguments α+2πkn\tfrac{\alpha + 2\pi k}{n}, for k=0,…,n−1k = 0, \ldots, n – 1. A vector of k and the formula, no loop:

The formula can be built with the robot’s idea: when you multiply complex numbers, the moduli multiply and the arguments add. You are looking for a z z that, raised to the 6th power, gives 8:

  • Its modulus raised to the 6th power has to give 8: the modulus is 86=2=1.4142 \sqrt[6]{8} = \sqrt{2} = 1.4142 , the same for all six corners.
  • Six times its argument has to give the argument of 8, which is 0°. But 360° or 720°… also work, because full turns leave the point where it was. Each extra turn is one k k in the formula: that is why the 2πk 2\pi k appears.
k k ArgumentCornerWhy
00∘ 0^\circ 1.4142 1.4142 no extra turn: on the x x axis
160∘ 60^\circ 0.7071+1.2247i 0.7071 + 1.2247i one turn shared among six: 360∘/6 360^\circ / 6
2120∘ 120^\circ −0.7071+1.2247i -0.7071 + 1.2247i 720∘/6 720^\circ / 6
3180∘ 180^\circ −1.4142 -1.4142 half a turn: the opposite corner
4240∘ 240^\circ −0.7071−1.2247i -0.7071 – 1.2247i 1440∘/6 1440^\circ / 6
5300∘ 300^\circ 0.7071−1.2247i 0.7071 – 1.2247i 1800∘/6 1800^\circ / 6

Why does it stop at k=5 k = 5 ? Because k=6 k = 6 gives 360∘ 360^\circ , the corner of k=0 k = 0 again, and from there on they all repeat. That is why there are exactly n n roots and why in the code k k goes from 0 to n−1 n – 1 .

Check you’ve got it: what would nth_roots(8, 4) plot?

A square of radius 1.6818 with its corners on the axes. Step by step: the modulus is 84=1.6818 \sqrt[4]{8} = 1.6818 ; the argument of 8 is 0, so the first corner is at 0°; and with 4 roots there is one every 90∘ 90^\circ : 1.6818 1.6818 , 1.6818i 1.6818i , −1.6818 -1.6818 and −1.6818i -1.6818i . Each one is the previous one times i i , the robot’s turn.

function r = nth_roots(w, n)
% NTH_ROOTS  The n nth roots of the complex number w, ordered by k = 0, ..., n-1.
%   With no output (nth_roots(w, n) on its own), it plots them as a polygon.
k = (0:n-1).';                                     % column of k
r = abs(w)^(1/n) * exp(1i * (angle(w) + 2*pi*k) / n);
if nargout == 0                                    % nobody collects the output: plot
    plot([r; r(1)], 'o-')                          % repeat the first to close it
    axis equal
    grid on
    title(sprintf('The %d roots of order %d of %s', n, n, num2str(w)))
end
end

Two new pieces:

  • nargout tells you how many outputs the caller asked for. If it is 0, the function does something else useful: it plots. Many MATLAB functions do this.
  • (0:n-1).' is a column: with .' and not ', out of habit (here k is real and it would make no difference, but in a function that works with complex numbers it is better not to mix them).
corners = nth_roots(8, 6)
check = norm(corners.^6 - 8)

Output:

corners =

   1.4142 + 0.0000i
   0.7071 + 1.2247i
  -0.7071 + 1.2247i
  -1.4142 + 0.0000i
  -0.7071 - 1.2247i
   0.7071 - 1.2247i

check =

   3.1264e-14

Modulus 86=2=1.4142\sqrt[6]{8} = \sqrt{2} = 1.4142 and a corner every 60∘60^\circ, starting at 0∘0^\circ because arg⁡8=0\arg 8 = 0. The check raises the six to the sixth power and sees that they give 8: the difference is of the order of 10−1410^{-14}.

Comparing with MATLAB: roots gives the roots of a polynomial, and those of z6−8z^6 – 8 are these same ones. But it returns them in another order, so before comparing you have to sort both lists the same way, for example by their argument:

r2 = roots([1 0 0 0 0 0 -8]);       % coefficients of z^6 - 8
[~, i1] = sort(angle(corners));
[~, i2] = sort(angle(r2));
difference = norm(corners(i1) - r2(i2))

Output:

difference =

   4.0693e-15

They match. Comparing two lists of roots without sorting them is a common mistake: they would give a large difference even though both are right.

And without asking for an output, the function plots (and, since the call has no semicolon, MATLAB also shows the result in ans):

figure
nth_roots(8, 6)

Output:

ans =

   1.4142 + 0.0000i
   0.7071 + 1.2247i
  -0.7071 + 1.2247i
  -1.4142 + 0.0000i
  -0.7071 - 1.2247i
   0.7071 - 1.2247i
The 6 roots of order 6 of 8MATLAB plot: six points joined into a regular hexagon centred at the origin, with a vertex at (1.4142, 0).−2−1012−1−0.500.51The 6 roots of order 6 of 8
The plot nth_roots makes when you ask for no output: a hexagon of radius 1.4142.

A regular hexagon of radius 1.4142 centred at the origin: the six corners of the rug.

Geometry with functions: distances and positions

Topic 8 computes distances with formulas. Programming them as functions forces you to decide how each thing is stored: a point as a column, a line as a point AA and a direction vector v\mathbf{v}, and a plane as a point AA and a normal vector n\mathbf{n}. With those decisions, the functions work just as well in the plane (2 coordinates) as in space (3).

Distance from a point to a line

The distance from PP to the line is the length of the part of AP→\overrightarrow{AP} perpendicular to v\mathbf{v}: you remove its projection onto v\mathbf{v}, as in Gram-Schmidt (block 2).

function d = dist_point_line(P, A, v)
% DIST_POINT_LINE  Distance from the point P to the line through A with direction v (in R^2 or R^3).
AP = P - A;
perp = AP - (dot(AP, v) / dot(v, v)) * v;     % what does not go in the direction of v
d = norm(perp);
end

The robot is at (3,2)(3, 2) and the sofa wall runs from (0,3)(0, 3) to (4,3)(4, 3) (the top side of the room):

robot = [3; 2];
d1 = dist_point_line(robot, [0; 3], [4; 0])
d2 = dist_point_line([1; 1; 1], [0; 0; 0], [1; 1; 0])   % also in space

Output:

d1 =

     1

d2 =

     1

1 m, as you can see by eye (the wall is the line y=3y = 3 and the robot is at y=2y = 2). The second one, in space: the point (1,1,1)(1, 1, 1) is at distance 1 from the line through the origin in the direction (1,1,0)(1, 1, 0), because its part in that direction is (1,1,0)(1, 1, 0) and (0,0,1)(0, 0, 1) is left over.

Inside, with the robot and the wall:

StepCalculationWhy
AP = P - A(3,2)−(0,3)=(3,−1) (3, 2) – (0, 3) = (3, -1) the arrow from a point on the wall to the robot
dot(AP, v) / dot(v, v)12/16=0.75 12 / 16 = 0.75 how much of that arrow goes along the wall, in multiples of v \mathbf{v}
projection0.75⋅(4,0)=(3,0) 0.75 \cdot (4, 0) = (3, 0) the closest point of the wall is 3 m further along, at (3,3) (3, 3)
perp(3,−1)−(3,0)=(0,−1) (3, -1) – (3, 0) = (0, -1) what is left points straight at the wall
norm(perp)1 1 its length is the distance

Dividing by norm(v) instead of by dot(v, v). It would give 3⋅(4,0)=(12,0) 3 \cdot (4, 0) = (12, 0) , a projection that leaves the room, and a distance of 82=9.055 \sqrt{82} = 9.055 . Since you then multiply by v \mathbf{v} again, you have to divide by its length twice: that is dot(v, v).

Distance from a point to a plane

With the normal it is a one-line formula: d=∣n⋅AP→∣∥n∥d = \dfrac{|\mathbf{n} \cdot \overrightarrow{AP}|}{\lVert \mathbf{n} \rVert}. The attic ceiling is a sloping plane through A=(0,0,2.5)A = (0, 0, 2.5) that goes down towards the back, with normal n=(0; 0.6; 0.8)\mathbf{n} = (0;\ 0.6;\ 0.8); the lamp hangs at P=(1,2,1.6)P = (1, 2, 1.6):

function d = dist_point_plane(P, A, n)
% DIST_POINT_PLANE  Distance from the point P to the plane through A with normal vector n.
d = abs(dot(n, P - A)) / norm(n);
end

With the lamp and the ceiling:

lamp = [1; 2; 1.6];
A = [0; 0; 2.5];  n = [0; 0.6; 0.8];
d = dist_point_plane(lamp, A, n)
foot = lamp - dot(n, lamp - A) / dot(n, n) * n    % the closest point of the ceiling
dot(n, foot - A)                                  % is it on the plane?

Output:

d =

    0.4800

foot =

    1.0000
    1.7120
    1.2160

ans =

     0

By hand: AP→=(1,2,−0.9)\overrightarrow{AP} = (1, 2, -0.9), n⋅AP→=0+1.2−0.72=0.48\mathbf{n} \cdot \overrightarrow{AP} = 0 + 1.2 – 0.72 = 0.48 and ∥n∥=1\lVert \mathbf{n} \rVert = 1, so the lamp is 0.48 m from the ceiling. The foot of the perpendicular is the closest point of the ceiling, and the last line checks that it really is on the plane: n⋅(foot−A)\mathbf{n} \cdot (\text{foot} – A) has to be 0 (it comes out as 0, or a number of the order of 10−1610^{-16}, depending on rounding).

Relative position of two lines, with rank

Topic 8 decides whether two lines in space coincide, are parallel, intersect or are skew with the ranks of {v1,v2}\{\mathbf{v}_1, \mathbf{v}_2\} and of {v1,v2,A1A2→}\{\mathbf{v}_1, \mathbf{v}_2, \overrightarrow{A_1A_2}\}. Programmed:

Before the code, the two ranks in words. The first one only asks whether the lines go in the same direction (1) or not (2). The second adds the arrow from a point on one line to a point on the other, and asks whether it brings anything new:

  • 1 and 1: same direction and the arrow goes that way too. The second point is on the first line: they coincide.
  • 1 and 2: same direction, but the arrow leaves it. Parallel.
  • 2 and 2: different directions and the arrow fits in their plane. They lie in one plane without being parallel: they intersect.
  • 2 and 3: the arrow leaves that plane. No plane contains both: they are skew.
function pos = line_position(r, s)
% LINE_POSITION  Relative position of two lines in R^3.
%   Each line is a struct with a point (field A) and a direction vector (field v).
r1 = rank([r.v s.v]);
r2 = rank([r.v s.v s.A - r.A]);
if r1 == 1 && r2 == 1
    pos = 'coincident';
elseif r1 == 1
    pos = 'parallel';
elseif r2 == 2
    pos = 'intersect';
else
    pos = 'skew';
end
end

The curtain rail runs at a height of 2.2 m along the back wall; a lamp cable comes straight down; a beam crosses the ceiling:

rail  = struct('A', [0; 3; 2.2], 'v', [1; 0; 0]);   % point and direction
beam  = struct('A', [0; 0; 2.4], 'v', [0; 1; 0]);
cable = struct('A', [1; 3; 0],   'v', [0; 0; 1]);
other = struct('A', [0; 0; 2.2], 'v', [2; 0; 0]);
same  = struct('A', [5; 3; 2.2], 'v', [-3; 0; 0]);
line_position(rail, beam)
line_position(rail, cable)
line_position(rail, other)
line_position(rail, same)

Output:

ans =

    'skew'

ans =

    'intersect'

ans =

    'parallel'

ans =

    'coincident'

Each line is a struct: a variable with named fields. struct('A', …, 'v', …) creates one with the fields A and v, and inside the function they are read as r.A and r.v. That way the function receives two lines and not four loose vectors in an order you have to remember. The four cases:

  • The rail (horizontal, xx axis, at 2.2 m) and the beam (yy axis, at 2.4 m) are skew: different directions and different heights, they never touch.
  • The rail and the vertical cable through x=1x = 1, y=3y = 3 intersect at (1,3,2.2)(1, 3, 2.2).
  • The rail and other are parallel: same direction ((2,0,0)(2, 0, 0) is twice (1,0,0)(1, 0, 0)) and another wall.
  • The rail and same coincide: it is the same line, described from another point and in the opposite direction.

The four cases, rank by rank

The calculations the function does inside. In all of them, r is the rail, with A=(0,3,2.2) A = (0, 3, 2.2) and v=(1,0,0) \mathbf{v} = (1, 0, 0) :

Pairs.A - r.Ar1r2Why
beam(0,−3,0.2) (0, -3, 0.2) 23the arrow rises 0.2 m, out of the horizontal plane of the two directions
cable(1,0,−2.2) (1, 0, -2.2) 22all three arrows have y=0 y = 0 : they fit in the back wall
other(0,−3,0) (0, -3, 0) 12(2,0,0) (2, 0, 0) is twice (1,0,0) (1, 0, 0) , but the arrow points to another wall
same(5,0,0) (5, 0, 0) 11the arrow also runs along the x x axis: the point is on the rail
Check you’ve got it: what does line_position(beam, cable) return?

‘skew’. Step by step: the directions (0,1,0) (0, 1, 0) and (0,0,1) (0, 0, 1) are different, so r1 is 2. The arrow from the beam to the cable is (1,3,−2.4) (1, 3, -2.4) , the only one with x x other than 0: it leaves the plane x=0 x = 0 of the two directions and r2 is 3. In the living room: the beam is at x=0 x = 0 and the cable comes down at x=1 x = 1 . They never touch.

The ceiling in 3D with plot3

plot3(x, y, z) is like plot with one more coordinate. The sloping ceiling is drawn by its edge (a four-corner polygon whose corners satisfy the equation of the plane), and the lamp and its perpendicular, as a point and a segment:

ceiling = [0 4 4 0 0;        % x of the ceiling corners (closed)
           0 0 3 3 0;        % y
           2.5 2.5 0.25 0.25 2.5];   % z: from 2.5 m to 0.25 m, on the plane
figure
plot3(ceiling(1,:), ceiling(2,:), ceiling(3,:), 'b-')
hold on
plot3(lamp(1), lamp(2), lamp(3), 'ro')
plot3([lamp(1) foot(1)], [lamp(2) foot(2)], [lamp(3) foot(3)], 'r--')
plot3([0 4 4 0 0], [0 0 3 3 0], zeros(1, 5), 'k:')    % the floor, for reference
axis equal
grid on
xlabel('x (m)'), ylabel('y (m)'), zlabel('z (m)')
title('The lamp and the sloping ceiling')
view(120, 25)
The lamp and the sloping ceilingMATLAB 3D plot: a tilted rectangle going down from 2.5 to 0.25 metres high, a red point at (1, 2, 1.6) and a dashed segment up to the ceiling.x (m)y (m)z (m)The lamp and the sloping ceiling
The edge of the sloping ceiling (blue), the floor (dotted), the lamp (red) and its perpendicular to the ceiling, 0.48 m long.

The zz of the corners comes from the equation of the plane: 0.6 y+0.8 (z−2.5)=00.6\,y + 0.8\,(z – 2.5) = 0, that is, z=2.5−0.75 yz = 2.5 – 0.75\,y, which gives 2.5 at y=0y = 0 and 0.25 at y=3y = 3 (the low part of the attic). view(120, 25) chooses the viewpoint (azimuth and elevation, in degrees). The default one, view(-37.5, 30), looks at the ceiling almost edge-on and it shows up as a line; with the mouse, in your MATLAB, you can rotate the plot. And axis equal matters again: without it, MATLAB stretches each axis separately and the perpendicular no longer looks perpendicular.

Common mistakes (with MATLAB’s real message)

1. Subtracting a point as a row and another as a column. It gives no error: it gives a matrix.

[1 2 3] - [0; 0; 2.5]

Output:

ans =

    1.0000    2.0000    3.0000
    1.0000    2.0000    3.0000
   -1.5000   -0.5000    0.5000

With points as columns in every function, P - A is a vector; if one arrives as a row, you get a 3×33 \times 3 matrix and dot or norm give meaningless numbers. One line at the start of the function prevents it: P = P(:); A = A(:); turns any vector into a column.

2. A plane with a zero normal. If the normal comes out as (0,0,0)(0, 0, 0) (for example, from the cross product of two parallel vectors), the distance divides by 0:

dist_point_plane(lamp, A, [0; 0; 0])

Output:

ans =

   NaN

NaN and no error: 0/00/0. Just like the Gauss without pivoting in block 1, the failure shows up far from where it starts. A check if norm(n) < 1e-12, error(...) in the function would make it visible.

3. Comparing roots without sorting them.

norm(corners - r2)

Output:

ans =

    5.0990

A 5.1 when both lists have the same roots. It is not a calculation error, but an ordering one.

  • Degrees where radians go: exp(1i*90) rotates by 90 radians. Use deg2rad or exp(1i*pi/2).
  • ' with complex numbers: it conjugates. To transpose, .'.
  • i as a counter before writing complex numbers: use 1i.

Try it in the MATLAB playground

In the site’s MATLAB playground you can try everything, plots included. This script moves the robot, computes the corners of the rug and measures the lamp:

% Robot, rug and lamp in the living room
pos = 0; heading = 1; route = pos;
for t = [4 3 4 3]
    pos = pos + t*heading;  route(end+1) = pos;  heading = heading*1i;
end
route
corners = roots_n(8, 6)
lamp = [1; 2; 1.6];  A = [0; 0; 2.5];  n = [0; 0.6; 0.8];
distance = abs(dot(n, lamp - A)) / norm(n)

function r = roots_n(w, n)
k = (0:n-1).';
r = abs(w)^(1/n) * exp(1i*(angle(w) + 2*pi*k)/n);
end

Things to look at:

  1. Change heading*1i to heading*(-1i): the robot turns right and goes round the room the other way (the stops pass through −3i-3i).
  2. Change roots_n(8, 6) to roots_n(-8, 3): one of the three cube roots of −8-8 is −2-2; find which one.
  3. Look at angle(corners) and convert it to degrees with rad2deg.
  4. Add plot(route, 'o-') and axis equal after route to see the route drawn.

And to move complex numbers with the mouse and see the product as a rotation, there is the Complex plane simulator.

Summary

PieceWhat forExample
1i, abs, angleWrite a complex number, modulus and argument (radians)abs(3 + 2i)
exp(1i*t)Rotate by t radians about the originz * exp(1i*deg2rad(30))
plot(z)Plot complex numbers: real against imaginaryplot(route, 'o-')
.' versus 'Transpose without / with conjugatingv.'
nargoutDo something else if no output is asked forif nargout == 0, plot(...), end
Line and plane as dataPoint + direction / point + normaldist_point_plane(P, A, n)
rank to decideRelative position of linesrank([v1 v2 A2 - A1])
structGroup named dataline = struct('A', A, 'v', v)
plot3, viewPlot in spaceplot3(x, y, z, 'b-')

Three ideas to take away:

  1. With complex numbers, the direction is a number and turning is multiplying. The robot takes three lines and no angles.
  2. Decide how you store each object before programming: points as columns, line = point + direction, plane = point + normal. With that, the functions work in 2D and in 3D.
  3. Compare lists in the same order and decide with ranks, not equalities. sort before norm, and rank instead of checking whether a determinant “is zero”.

This block completes the theory of the MATLAB intensive course. Now it is your turn: in the block 4 exercises you will program equations with complex numbers, the angle between lines and planes, reflections and a plotted conic, with commented solutions, “What is wrong here?” and a cheat sheet. And if you want to go over it from the start, the intensive course begins at block 1, with your own Gauss-Jordan.

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

Next step: exercisesComplex numbers and geometry in MATLAB — exercises to program nth roots, draw a star logo and check the cables of a zip line (and the vector products from lab assignment 1)Mock exam: the AG practical examAG practical mock examCheat sheet: the block on one page, to reviewCheat sheetLab assignments: the block's functions and a model scriptFor your lab assignments