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.
Table of Contents
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 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, , can be stored as the complex number , 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 roots of a complex number and, if you do not ask for an output, plots them (topic 7);dist_point_line,dist_point_planeandline_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 , the complex number . What happens if you multiply it by ?
, and since , you get . The point has moved to : 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: . The point always goes to , which is the rule for a 90° rotation. And the distance to the corner does not change (both are at ); 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. has modulus 1 (it does not stretch) and argument 90° (it turns 90°); has modulus 1 and argument : it turns . 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 , the point . Step by step: . The modulus of is 1, so the distance is still ; its argument is , so the angle drops from 33.69° to . Multiplying by turns left; by , 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: and . angle returns radians, between and , and it also looks at the quadrant (unlike atan(b/a)); rad2deg and deg2rad convert between the two without you having to remember .
Three things worth knowing before you program:
- Write
1i, noti.iandjare only as long as you do not use them as variables. After afor i = 1:3,2 + 3*igives 11.3ior3 + 2i(a number stuck to thei) are always complex, but1ion its own is the safe form. - The apostrophe conjugates. With complex numbers,
v'transposes and conjugates; to transpose without conjugating you usev.'. 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 anglet. Multiplying by it rotates bytradians 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 : the real part is not exactly 0 (it is of the order of , because of the rounding of ), 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 to , the rotation from topic 7.
The robot program: a loop of complex numbers
The robot leaves the corner heading east (direction ), moves forward, bumps into something, turns 90 degrees to the left (multiplies its direction by ) 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: . The direction goes through and back to , because . The trace table, pass by pass:
| Pass | legs(k) | heading before | pos after | heading after |
|---|---|---|---|---|
| 1 | 4 | |||
| 2 | 3 | |||
| 3 | 4 | |||
| 4 | 3 |
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 ).
| Pass | pos | heading | Why |
|---|---|---|---|
| 1 | facing east: 4 m along the bottom wall; it bumps and turns north | ||
| 2 | 3 m upwards; means facing west | ||
| 3 | 4 m to the left, goes back to 0; now it faces south | ||
| 4 | 3 m down, to the corner, facing east again |
heading always has modulus 1, because multiplying by 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: , 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 axis and the imaginary part on the 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 4 m by 3 m rectangle of the living room, travelled anticlockwise: turning left is multiplying by , and 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 (the robot turning on the spot, or a chair round the table), you take to the origin, rotate and bring it back: .
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: ; times , ; plus , .
The same calculation for the first leg, uncompressed. is three steps:
| Step | Calculation | Why |
|---|---|---|
| Subtract the center | the table becomes the origin | |
| Turn | multiplying can only turn about the origin, which is now the table | |
| Add the center | it undoes the first step: the table goes back to its place |
Turning without subtracting the center, . With the first leg it gives : 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 , the third one in the output. Step by step: subtract the center, ; turn, ; add the center, . 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 roots of have modulus and arguments , for . 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 that, raised to the 6th power, gives 8:
- Its modulus raised to the 6th power has to give 8: the modulus is , 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 in the formula: that is why the appears.
| Argument | Corner | Why | |
|---|---|---|---|
| 0 | no extra turn: on the axis | ||
| 1 | one turn shared among six: | ||
| 2 | |||
| 3 | half a turn: the opposite corner | ||
| 4 | |||
| 5 |
Why does it stop at ? Because gives , the corner of again, and from there on they all repeat. That is why there are exactly roots and why in the code goes from 0 to .
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 ; the argument of 8 is 0, so the first corner is at 0°; and with 4 roots there is one every : , , and . Each one is the previous one times , 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:
nargouttells 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 (herekis 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 and a corner every , starting at because . The check raises the six to the sixth power and sees that they give 8: the difference is of the order of .
Comparing with MATLAB: roots gives the roots of a polynomial, and those of 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
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 and a direction vector , and a plane as a point and a normal vector . 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 to the line is the length of the part of perpendicular to : you remove its projection onto , 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 and the sofa wall runs from to (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 and the robot is at ). The second one, in space: the point is at distance 1 from the line through the origin in the direction , because its part in that direction is and is left over.
Inside, with the robot and the wall:
| Step | Calculation | Why |
|---|---|---|
AP = P - A | the arrow from a point on the wall to the robot | |
dot(AP, v) / dot(v, v) | how much of that arrow goes along the wall, in multiples of | |
| projection | the closest point of the wall is 3 m further along, at | |
perp | what is left points straight at the wall | |
norm(perp) | its length is the distance |
Dividing by norm(v) instead of by dot(v, v). It would give , a projection that leaves the room, and a distance of . Since you then multiply by 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: . The attic ceiling is a sloping plane through that goes down towards the back, with normal ; the lamp hangs at :
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: , and , 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: has to be 0 (it comes out as 0, or a number of the order of , 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 and of . 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, axis, at 2.2 m) and the beam ( axis, at 2.4 m) are skew: different directions and different heights, they never touch.
- The rail and the vertical cable through , intersect at .
- The rail and
otherare parallel: same direction ( is twice ) and another wall. - The rail and
samecoincide: 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 and :
| Pair | s.A - r.A | r1 | r2 | Why |
|---|---|---|---|---|
| beam | 2 | 3 | the arrow rises 0.2 m, out of the horizontal plane of the two directions | |
| cable | 2 | 2 | all three arrows have : they fit in the back wall | |
| other | 1 | 2 | is twice , but the arrow points to another wall | |
| same | 1 | 1 | the arrow also runs along the 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 and are different, so r1 is 2. The arrow from the beam to the cable is , the only one with other than 0: it leaves the plane of the two directions and r2 is 3. In the living room: the beam is at and the cable comes down at . 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 of the corners comes from the equation of the plane: , that is, , which gives 2.5 at and 0.25 at (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 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 (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: . 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. Usedeg2radorexp(1i*pi/2). 'with complex numbers: it conjugates. To transpose,.'.ias a counter before writing complex numbers: use1i.
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:
- Change
heading*1itoheading*(-1i): the robot turns right and goes round the room the other way (the stops pass through ). - Change
roots_n(8, 6)toroots_n(-8, 3): one of the three cube roots of is ; find which one. - Look at
angle(corners)and convert it to degrees withrad2deg. - Add
plot(route, 'o-')andaxis equalafterrouteto 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
| Piece | What for | Example |
|---|---|---|
1i, abs, angle | Write a complex number, modulus and argument (radians) | abs(3 + 2i) |
exp(1i*t) | Rotate by t radians about the origin | z * exp(1i*deg2rad(30)) |
plot(z) | Plot complex numbers: real against imaginary | plot(route, 'o-') |
.' versus ' | Transpose without / with conjugating | v.' |
nargout | Do something else if no output is asked for | if nargout == 0, plot(...), end |
| Line and plane as data | Point + direction / point + normal | dist_point_plane(P, A, n) |
rank to decide | Relative position of lines | rank([v1 v2 A2 - A1]) |
struct | Group named data | line = struct('A', A, 'v', v) |
plot3, view | Plot in space | plot3(x, y, z, 'b-') |
Three ideas to take away:
- With complex numbers, the direction is a number and turning is multiplying. The robot takes three lines and no angles.
- 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.
- Compare lists in the same order and decide with ranks, not equalities.
sortbeforenorm, andrankinstead 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


