Complex 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)
In lab assignment 1 of AG (Linear Algebra and Geometry) there was a question about which operations are valid between two vectors of the same size, and I only half got it: I ticked addition and subtraction, and not the other two. It sounds trivial until you program geometry: there every distance and every angle is a product of vectors, and mixing up u*v with dot(u, v) or with u.*v is the difference between a number, an error and a vector you weren’t expecting. This last block of the intensive course is about that, with complex numbers and with lines in space.
Table of Contents
How to use this article
The algebra is taken as known: binomial and polar form, nth roots, lines and planes in space and their relative positions are in Complex numbers and Affine space. Here you program: functions that work with complex numbers, vectors of solutions generated in one go without a loop, geometry functions that decide with ranks, and plots in 2D and 3D. The commands are in the theory of this block, MATLAB intensive 4: complex numbers and geometry.
There are two examples, one for each half of the topic: the star logo of a faculty club, which comes from the fifth roots of a number, and the zip line at the adventure park, with two cables that must not touch.
- Level 1 (reproduce): modulus, argument, conjugate and rotations with complex numbers, and what comes out.
- Level 2 (write the function):
nth_roots, which gives the nth roots, and two geometry functions: the distance from a point to a line and the relative position of two lines. - Level 3 (full lab assignment): the logo and the zip line step by step, with plots and quiz questions.
- Folded solutions; then “What is wrong here?” and the code-reading quiz.
All the code was run once with the interpreter of the website’s MATLAB environment, which gives the same outputs as MATLAB R2025a. The plots are drawn with the data that those commands produce.
Level 1: complex numbers that rotate
Exercise 1. With : a) Write the commands that give its modulus, its argument in radians and in degrees, and its conjugate. b) Multiply by and explain what happened to the point. c) Write in binomial form the complex number with modulus 2 and argument 60° using exp. d) Predict what angle(-1) and angle(-1 - 0i) return, and check the first one.
Expected result: modulus 5, argument 0.9273 rad = 53.1301°, conjugate ; , the same point rotated by 90°; ; angle(-1) is .
The imaginary unit is written 1i (i also works, but if you used i as a loop counter it is no longer the imaginary unit). angle gives radians; rad2deg turns them into degrees.
Level 2: nth roots and geometry as functions
Exercise 2. a) Write w = nth_roots(z, n) that returns in a column the nth roots of , without a loop: generate in a vector and compute them all at once. Test it with the fifth roots of 32 and check that, raised to the 5th power, they give 32. b) Write [d, Q] = dist_line(P, A, u): the distance from point to the line through with direction , and the point on the line closest to (everything as columns). c) Write t = line_position(A, u, B, v), which returns 'coincident', 'parallel', 'intersecting' or 'skew' using only two ranks.
Expected result: the fifth roots of 32 are , one of them the real number 2, and the error of w.^5 - 32 is around ; the other two functions are tested in level 3.
k = (0:n-1)' is a column, and exp(1i*(angle(z) + 2*pi*k)/n) does the computations at once. For the lines: tells you whether they are parallel, and whether they lie in one plane.
Level 3: a full lab assignment
Shaped like the lab assignment guides on the campus: one part, one command or a short answer. Use the functions from level 2.
Exercise 3. The logo and the zip line.
- a) The club’s logo is a five-pointed star inscribed in a circle of radius 2. The vertices are the fifth roots of 32. Draw the star by joining every second vertex (1, 3, 5, 2, 4 and back to 1) and mark the five vertices with circles.
- b) For the “rotated” version of the logo, each point has to land where the gap between two points was. Which complex number do you multiply all the vertices by? Write the command.
- c) The zip line goes from tree to tree (in metres). Write the cable’s direction and its length. A street lamp has its bulb at : how far does the cable pass from it, and through which point?
- d) There is a second cable from with direction . What is the relative position of the two cables? If they collide, raise point by 1 m and check again.
- e) Quiz questions: (1) True or false: with
uandvrow vectors of the same size,u*vgives their dot product. (2) Fill in: to multiply two vectors element by element you writeu___v. (3) How many fourth roots does have and what is their modulus?
Expected result: in b), (a 36° rotation); the cable is 50.64 m long and passes 4.03 m from the bulb, through the point ; the two cables are intersecting (they meet at ), and with one metre higher they are skew and don’t touch.
The angle between two consecutive points is ; the gap is halfway. For the closest point, project onto .
What is wrong here?
Snippet 1: the product that isn’t a dot product (my lab assignment 1)
u = [40 30 -8]; w = [20 10 -3]; p = u * w
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.
u and w are rows, and * is the matrix product: it needs the columns of the first (3) to match the rows of the second (1). This is the “valid or not valid” from my lab assignment quiz: with two rows, u*w isn’t valid.
Writing u*w meaning the dot product. The three things that get mixed up: dot(u, w) or u*w' give the dot product (a number); u.*w gives the element-by-element product (a vector); u*w only works if the dimensions fit.
dot(u, w), u * w', u .* w
Output:
ans =
1124
ans =
1124
ans =
800 300 24
Snippet 2: the i that was no longer imaginary
for i = 1:3 % ... any loop with the counter i end z = 2 + 3*i
Output:
z =
11
I wanted the complex number and got 11: after the loop, i is a variable equal to 3, and 3*i is 9.
Using i (or j) as a counter and then as the imaginary unit. Always write 1i: a variable can’t hide it.
z = 2 + 3i
Output:
z = 2.0000 + 3.0000i
Snippet 3: the roots that come out as a row
function w = nth_roots_bad(z, n) k = 0:n-1; w = abs(z)^(1/n) * exp(1i*(angle(z) + 2*pi*k)/n); end
w = nth_roots_bad(-16, 4); size(w) P = [w; 0]
Output:
ans =
1 4
Dimensions of arrays being concatenated are not consistent.
The function computes correctly, but it returns a row (k = 0:n-1 is a row). The caller expected a column and, when adding a point underneath with ;, the dimensions don’t fit.
Decide the shape of the outputs and write it in the function’s comment (“returns a column”). Here k = (0:n-1)' is enough. And test each function with size as well as with the numbers.
Solutions
Exercise 1
Show the solution to exercise 1
z = 3 + 4i; abs(z), angle(z), rad2deg(angle(z)), conj(z) z * exp(1i*pi/2) w = 2*exp(1i*pi/3) angle(-1)
Output:
ans =
5
ans =
0.9273
ans =
53.1301
ans =
3.0000 - 4.0000i
ans =
-4.0000 + 3.0000i
w =
1.0000 + 1.7321i
ans =
3.1416
a) ; the argument is because it is in the first quadrant: 0.9273 rad, 53.13°. b) Multiplying by rotates by 90° without changing the modulus: . c) . d) angle(-1) is : MATLAB gives the argument in . With -1 - 0i you get , because zero has a sign; it is one of those quirks you’d rather know than discover in a quiz.
Why it is done this way: exp(1i*theta) is used and not cos(theta) + 1i*sin(theta) because it is shorter and you can’t get the function wrong in one of the two parts. And rad2deg rather than *180/pi for readability.
The approach to b), before the calculation: the obvious route would be to convert to polar form, add 90° to the argument and go back to binomial form. There’s no need, because is exactly , and multiplying by means swapping the two parts and adding a minus sign: . And since the modulus of is 1, the point gets neither closer to nor further from the origin: it only rotates. If you repeat the rotation, after four steps you’re back where you started:
z = 3 + 4i; turns = z * 1i.^(0:4) abs(turns)
Output:
turns =
3.0000 + 4.0000i -4.0000 + 3.0000i -3.0000 - 4.0000i 4.0000 - 3.0000i 3.0000 + 4.0000i
ans =
5 5 5 5 5
The second step is (180°) and the fourth goes back to , because . The five moduli are all 5: rotating doesn’t change the distance to the origin.
Exercise 2
Show the solution to exercise 2
function w = nth_roots(z, n)
% The n nth roots of z, in a COLUMN.
r = abs(z)^(1/n); % common modulus
k = (0:n-1)'; % k = 0, 1, ..., n-1 as a column
w = r * exp(1i*(angle(z) + 2*pi*k)/n); % all n at once
end
function [d, Q] = dist_line(P, A, u)
% Distance from P to the line A + t*u, and the closest point Q on the line.
t = dot(P - A, u) / dot(u, u); % projection of AP onto u
Q = A + t*u;
d = norm(P - Q);
end
function t = line_position(A, u, B, v)
% Relative position of the lines A + s*u and B + t*v (everything as columns).
r1 = rank([u v]); % proportional directions?
r2 = rank([u v B-A]); % in the same plane?
if r1 == 1 && r2 == 1
t = 'coincident';
elseif r1 == 1
t = 'parallel';
elseif r2 == 2
t = 'intersecting';
else
t = 'skew';
end
end
w = nth_roots(32, 5) max(abs(w.^5 - 32))
Output:
w = 2.0000 + 0.0000i 0.6180 + 1.9021i -1.6180 + 1.1756i -1.6180 - 1.1756i 0.6180 - 1.9021i ans = 3.5527e-14
The five roots have modulus 2 and are 72° apart. The check gives : zero apart from rounding. Look at the + 0.0000i in the first one: it is the real number 2 with a tiny imaginary leftover, and that is why you check with a tolerance and not with == 2.
The picture shows the decision table of line_position: two ranks and four cases.
Why it is done this way:
nth_rootshas no loop:kis a vector and the formula is applied to all its elements. It is MATLAB’s natural style and it is faster.- In
dist_line, is the projection of onto (the one from block 2), and is its foot. The distance is . line_positiondoesn’t solve any system: the two ranks already tell it everything. The lines are coplanar if fits in the plane of and (rank 2) and parallel if and are proportional (rank 1).
How I would mark it (rough breakdown, my own):
| What is assessed | Points |
|---|---|
nth_roots without a loop and returning a column | 1.5 |
Check with w.^n and a tolerance | 0.5 |
dist_line with a projection and two outputs | 1.5 |
line_position with two ranks and the four cases | 1.5 |
Why dist_line projects instead of using the cross product formula, : that formula gives the distance, but not the point , and the function has to return both. With the projection, a single number gives you both things. The idea in words: of all the points on the line, the closest one to is the one where is perpendicular to the line. Traced with the street lamp from exercise 3:
| Command | Result | Why |
|---|---|---|
P - A | The vector from tree to the bulb | |
dot(P - A, u) | 1124 | 800 + 300 + 24: how much of that vector goes in the direction of the cable |
dot(u, u) | 2564 | It is the length of squared: you divide by it so that doesn’t depend on how long is |
t | 0.4384 | is 43.8 % of the way from to |
Q = A + t*u | You move times from | |
d = norm(P - Q) | 4.0328 | The length of the perpendicular segment |
Since , is tree and is tree . With 0.4384, the closest point is on the actual cable; outside , the 4.03 m would be the distance to the line, not to the cable.
In line_position, the order of the ifs is not arbitrary. The obvious thing would be to ask first whether they are parallel with r1 == 1, but two coincident lines also have proportional directions: they would go down that branch and you’d get ‘parallel’. That’s why the most demanding case, both ranks equal to 1, goes first.
With the cables, r1 is 2 (they aren’t parallel), and with the original r2 is also 2: fits in the plane of the two directions and the cables meet. With the extra metre it is 3: there is no common plane any more and they are skew.
Exercise 3
Show the solution to exercise 3
a)
w = nth_roots(32, 5);
order = [1 3 5 2 4 1];
e = w(order);
plot(real(e), imag(e), 'r-')
hold on
plot(real(w), imag(w), 'bo')
axis equal
title('Logo star')
plot doesn’t handle complex numbers usefully: you pass it the real part as and the imaginary part as . Joining every second vertex (1, 3, 5, 2, 4) instead of consecutive ones is what turns the pentagon into a star. This is the figure:
b) The points are every 72°, so the gap between two points is at 36°: you multiply by . Multiplying by a complex number of modulus 1 rotates without changing the size.
w2 = w * exp(1i*pi/5); rad2deg(angle(w2(1)))
Output:
ans =
36
The first point, which was at 0°, moves to 36°.
c)
A = [0; 0; 12]; B = [40; 30; 4]; u = B - A norm(u) L = [20; 10; 9]; [d, Q] = dist_line(L, A, u)
Output:
u =
40
30
-8
ans =
50.6360
d =
4.0328
Q =
17.5351
13.1513
8.4930
The cable is 50.64 m long () and passes 4.03 m from the bulb, through the point : at that height the cable is half a metre below the bulb, and almost four metres away sideways.
d)
C = [0; 30; 10]; v = [40; -30; -4]; line_position(A, u, C, v) line_position(A, u, C + [0; 0; 1], v)
Output:
ans =
'intersecting'
ans =
'skew'
With the original they are intersecting: the two cables meet. You can see it with half of each: and , the same point. Raising one metre, they are no longer in the same plane and they are skew: one passes over the other without touching.
e) (1) False: with two rows, u*v gives a dimensions error (snippet 1); the dot product is dot(u, v) or u*v'. (2) .*. (3) Four roots, with modulus , 90° apart and starting at 45°.
Why it is done this way: in d) the decision is made with the ranks of line_position and not “by computing the intersection point and seeing whether it exists”, which means solving a system of three equations in two unknowns. And the check with the midpoints comes from reading the result: if they intersect, look for where.
The order [1 3 5 2 4 1] from a), vertex by vertex. Root number is at the angle :
| Vertex | Angle | Why |
|---|---|---|
| 1 | 0° | You start at the real number 2 |
| 3 | 144° | You skip 2: two steps of 72° |
| 5 | 288° | Another 144° |
| 2 | 72° | 432°, one full turn plus 72° |
| 4 | 216° | Another 144° |
| 1 | 0° | You go back to the start and close it |
Each stroke moves 144°, twice the step between vertices, and that’s why the line crosses through the inside and you get the star. Moving 72° each time ([1 2 3 4 5 1]) you’d draw the pentagon.
Forgetting the final 1. plot only joins consecutive points of the vector, so without it the star is missing the stroke from vertex 4 to 1.
In b), the obvious thing would be to rotate one step between points, 72°, but that takes each vertex to where the next one was: the points are the same and the logo looks identical. What you need is half a step, 36°.
Check you’ve got it: would multiplying the vertices by -1 work instead of rotating them 36°?
Yes: the rotated logo comes out the same. Step by step: rotates 180°, and the vertices go from 0°, 72°, 144°, 216° and 288° to 180°, 252°, 324°, 36° and 108°, which are exactly the five gaps. It works because 180° is 36° plus two steps of 72°. Even so, is easier to understand: it states the rotation you’re after.
Quiz: read the code
Ten code-reading questions, like the ones in the lab assignment quizzes on the campus. Every output was checked with the interpreter.
What does this code print?
z = -3 + 4i; abs(z)
- ans = 5
- ans = 1
- ans = 3.0000 + 4.0000i
- ans = 25
Solution
Answer: ans = 5
abs of a complex number is its modulus, .
What does this code print?
z = 2i; w = z * 1i
- w = -2
- w = 2
- w = 0.0000 + 2.0000i
- w = 3i
Solution
Answer: w = -2
Multiplying by is a 90° anticlockwise rotation.
What does this code print?
for i = 1:2 end z = 1 + i
- z = 3
- z = 1.0000 + 1.0000i
- z = 2
- An error
Solution
Answer: z = 3
It is snippet 2: write 1i for the imaginary unit and you won’t have this problem.
What does this code print?
k = (0:3)'; size(k)
- ans = 4 1
- ans = 1 4
- ans = 4
- ans = 3 1
Solution
Answer: ans = 4 1
The apostrophe turns the row into a column. It is what makes nth_roots return a column.
With u = [1 2 3] and v = [4 5 6] (rows), which commands give the dot product, 32?
- dot(u, v)
- u * v’
- u * v
- u .* v
Solution
Answer: dot(u, v) · u * v’
. sum(u .* v) would also give 32.
What does this code print?
u = [1; 2; 0]; v = [2; 4; 0]; rank([u v])
- ans = 1
- ans = 2
- ans = 3
- ans = 0
Solution
Answer: ans = 1
With , the lines are parallel or coincident; the second rank decides.
About the article’s line_position function:
- If both ranks are 2, the lines meet at a point.
- If the lines are skew, the second rank is 2.
- It needs the points and directions as columns.
- To know whether they intersect it solves a system.
Solution
- T — If both ranks are 2, the lines meet at a point.
- F — If the lines are skew, the second rank is 2.
- T — It needs the points and directions as columns.
- F — To know whether they intersect it solves a system.
They are skew when the second rank is 3: they don’t fit in one plane. The function only uses ranks; [u v B-A] joins three columns.
How many elements does nth_roots(16, 4) have with the article’s function, and what is their modulus?
- 4 roots of modulus 2
- 1 root, 2
- 2 roots, ±2
- 4 roots of modulus 4
Solution
Answer: 4 roots of modulus 2
The fourth roots of 16 are 2, 2i, −2 and −2i: a square of radius 2.
Complete the command that rotates every complex number in the vector w by 45°:
w2 = w * ____(1i*____);
Words:
- exp
- abs
- pi/4
- angle
- 45
- pi/2
Solution
w2 = w * exp(1i*pi/4);
A rotation is multiplying by with in radians: 45° = .
What does this code print?
A = [0; 0; 0]; u = [1; 0; 0]; P = [3; 4; 0]; t = dot(P - A, u) / dot(u, u); d = norm(P - (A + t*u))
- d = 4
- d = 5
- d = 3
- d = 0
Solution
Answer: d = 4
It is dist_line without the function: project onto , get the foot and measure.
Try it in the MATLAB environment
Open the MATLAB environment, paste the commands of exercise 3 and, at the end, the three functions from exercise 2. Then:
- Change the star to a seven-pointed one: seventh roots and order
[1 3 5 7 2 4 6 1]. Does jumping every second vertex work with any number of points? - Compute
nth_roots(-16, 4)and check withsizethat it is a column. - Find a point for the second cable that makes it parallel to the first, and check that
line_positiondetects it. - Draw both cables with
plot3([A(1) B(1)], [A(2) B(2)], [A(3) B(3)])(and anotherplot3for the second one, withhold on). In the website’s environment you get a fixed perspective view; on your desktop MATLAB you can rotate it with the mouse.
For your lab assignments
This block has no lab assignment of its own on the campus (there are four and they stop at transformations), but complex numbers and geometry are in the exam and in the quizzes, and what they ask for is programmed the same way. This model script brings today’s work together; change only the data.
%% Complex numbers and geometry: template format short %% 1. A complex number in both forms z = -2 + 2i; modulus = abs(z), argument_degrees = rad2deg(angle(z)) w = nth_roots(z, 3) % cube roots, as a column %% 2. Lines in space (points and directions as columns) A = [1; 0; 2]; u = [2; 1; -1]; B = [0; 1; 1]; v = [1; 1; 0]; position = line_position(A, u, B, v) [d, Q] = dist_line(B, A, u) % distance from point B to line 1 %% 3. Angle between the two directions (between 0 and 90 degrees) ang = acosd(abs(dot(u, v)) / (norm(u) * norm(v))) %% ---- functions (always at the end) ---- function w = nth_roots(z, n) r = abs(z)^(1/n); k = (0:n-1)'; w = r * exp(1i*(angle(z) + 2*pi*k)/n); end function [d, Q] = dist_line(P, A, u) t = dot(P - A, u) / dot(u, u); Q = A + t*u; d = norm(P - Q); end function t = line_position(A, u, B, v) r1 = rank([u v]); r2 = rank([u v B-A]); if r1 == 1 && r2 == 1, t = 'coincident'; elseif r1 == 1, t = 'parallel'; elseif r2 == 2, t = 'intersecting'; else, t = 'skew'; end end
Output:
modulus =
2.8284
argument_degrees =
135
w =
1.0000 + 1.0000i
-1.3660 + 0.3660i
0.3660 - 1.3660i
position =
'skew'
d =
1.7321
Q =
1
0
2
ang =
30.0000
Three details that tend to cost points:
- The angle between two lines is taken between 0° and 90°: that is why there is an
absinsideacosd. Without it, two lines at 60° could come out at 120°. - Everything as columns: points and directions like
[1; 0; 2]. The functions join vectors with[u v], and that needs columns. - The roots, with their
size: if a quiz asks for “the root with the smallest argument” or “the second one”, first look at the order your function returns them in (here, from upwards).
What next?
With this block the MATLAB intensive course ends. If the complex-number or geometry functions gave you trouble, the theory is in MATLAB intensive 4: complex numbers and geometry, and the three previous blocks start with matrices and systems. For the paper part of the AG exam, the two mock exams, theory and practical, and the Complex plane simulator, where you see the nth roots as a rotating polygon.
Cheat sheet: complex numbers and geometry in MATLAB
The essentials in 30 seconds: the imaginary unit is 1i; abs, angle (radians) and conj give the modulus, argument and conjugate; multiplying by exp(1i*theta) rotates; the nth roots come out without a loop with k = (0:n-1)'. In geometry, everything as columns, dot for the dot product and ranks for relative positions.
| I want… | Code | Watch out |
|---|---|---|
| A complex number | z = 3 + 4i | 1i better than i |
| Modulus and argument | abs(z), angle(z) | angle in radians, from to |
| In degrees | rad2deg(angle(z)) | |
| From polar to binomial | r*exp(1i*theta) | theta in radians |
| Rotate by | z * exp(1i*theta) | Modulus 1: the size doesn’t change |
| nth roots | abs(z)^(1/n)*exp(1i*(angle(z)+2*pi*k)/n) | k = (0:n-1)' |
| Plot complex numbers | plot(real(w), imag(w), 'o'), axis equal | |
| Dot product | dot(u, v) or u'*v (columns) | u*v with two columns gives an error |
| Element by element | u .* v | Gives a vector |
| Cross product | cross(u, v) | Only in 3D |
| Point-line distance | dist_line(P, A, u) | Or norm(cross(P-A, u))/norm(u) |
| Position of two lines | rank([u v]), rank([u v B-A]) | 1 = parallel; 3 = skew |
| Plot in 3D | plot3(x, y, z) | Rotate the figure with the mouse |
Templates for the exercises:
- Roots: common modulus →
kas a column → vectorised formula → checkw.^nwith a tolerance. - Polygons and stars: complex vertices → index with the drawing order →
plot(real, imag)→axis equal. - Lines: points and directions as columns → two ranks → case → if they intersect, find the point.
| Symptom | Likely cause |
|---|---|
Incorrect dimensions for matrix multiplication | u*v with two row vectors: use dot(u, v) |
A complex number that comes out real (11 instead of 2 + 3i) | i is a variable from an earlier loop |
Dimensions of arrays being concatenated are not consistent | A function returns a row when you expected a column |
| The star comes out as a pentagon | You joined consecutive vertices, not every second one |
| An angle between lines over 90° | The abs of the dot product is missing |
+ 0.0000i on a number that should be real | Rounding leftover: compare with a tolerance |
Before handing it in, ask yourself:
- Have I used
1iand notifor the imaginary unit? - Do my functions return the shape they say (row or column), and have I checked it with
size? - Is every product of vectors the one I want:
dot,.*orcross? - Have I decided relative positions with ranks and checked the result with a point?
Did this article help you? Here is how you can support SergioLearns →
Ready for the exam?AG practical mock exam — The AG practical exam on paper, with MATLAB to check every partBlock theory: Complex numbers, nth roots, distances and plot3Complex numbers and geometry in MATLABCheat sheet: the block on one page, to reviewCheat sheetLab assignments: the block's functions and a model scriptFor your lab assignments


