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.

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.

  1. Level 1 (reproduce): modulus, argument, conjugate and rotations with complex numbers, and what comes out.
  2. 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.
  3. Level 3 (full lab assignment): the logo and the zip line step by step, with plots and quiz questions.
  4. 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 z=3+4iz = 3 + 4i: a) Write the commands that give its modulus, its argument in radians and in degrees, and its conjugate. b) Multiply zz by eiπ/2e^{i\pi/2} 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 3−4i3 – 4i; z⋅eiπ/2=−4+3iz \cdot e^{i\pi/2} = -4 + 3i, the same point rotated by 90°; 2eiπ/3=1+1.7321i2e^{i\pi/3} = 1 + 1.7321i; angle(-1) is π\pi.

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 nn nth roots of zz, without a loop: generate k=0,…,n−1k = 0, \dots, n-1 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 PP to the line through AA with direction u⃗\vec u, and the point QQ on the line closest to PP (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 2ei2πk/52e^{i 2\pi k/5}, one of them the real number 2, and the error of w.^5 - 32 is around 10−1410^{-14}; 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 nn computations at once. For the lines: rank⁡(u⃗,v⃗)\operatorname{rank}(\vec u, \vec v) tells you whether they are parallel, and rank⁡(u⃗,v⃗,AB→)\operatorname{rank}(\vec u, \vec v, \overrightarrow{AB}) 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 A=(0,0,12)A = (0, 0, 12) to tree B=(40,30,4)B = (40, 30, 4) (in metres). Write the cable’s direction and its length. A street lamp has its bulb at L=(20,10,9)L = (20, 10, 9): how far does the cable pass from it, and through which point?
  • d) There is a second cable from C=(0,30,10)C = (0, 30, 10) with direction v⃗=(40,−30,−4)\vec v = (40, -30, -4). What is the relative position of the two cables? If they collide, raise point CC by 1 m and check again.
  • e) Quiz questions: (1) True or false: with u and v row vectors of the same size, u*v gives their dot product. (2) Fill in: to multiply two vectors element by element you write u ___ v. (3) How many fourth roots does −16-16 have and what is their modulus?

Expected result: in b), eiπ/5e^{i\pi/5} (a 36° rotation); the cable is 50.64 m long and passes 4.03 m from the bulb, through the point (17.54,13.15,8.49)(17.54, 13.15, 8.49); the two cables are intersecting (they meet at (20,15,8)(20, 15, 8)), and with CC one metre higher they are skew and don’t touch.

The angle between two consecutive points is 360°/5=72°360°/5 = 72°; the gap is halfway. For the closest point, project AL→\overrightarrow{AL} onto u⃗\vec u.

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 1×31 \times 3 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 2+3i2 + 3i 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) ∣z∣=9+16=5|z| = \sqrt{9 + 16} = 5; the argument is arctan⁡(4/3)\arctan(4/3) because it is in the first quadrant: 0.9273 rad, 53.13°. b) Multiplying by eiπ/2=ie^{i\pi/2} = i rotates by 90° without changing the modulus: (3+4i) i=3i+4i2=−4+3i(3 + 4i)\,i = 3i + 4i^2 = -4 + 3i. c) 2(cos⁡60°+isin⁡60°)=1+3 i2(\cos 60° + i \sin 60°) = 1 + \sqrt3\,i. d) angle(-1) is π\pi: MATLAB gives the argument in (−π,π](-\pi, \pi]. With -1 - 0i you get −π-\pi, 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 z z to polar form, add 90° to the argument and go back to binomial form. There’s no need, because eiπ/2 e^{i\pi/2} is exactly i i , and multiplying by i i means swapping the two parts and adding a minus sign: (a+bi) i=−b+ai (a + bi)\,i = -b + ai . And since the modulus of i i 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 −z -z (180°) and the fourth goes back to z z , because i4=1 i^4 = 1 . 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 3.6⋅10−143.6 \cdot 10^{-14}: 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.

Relative position of two lines with ranks2 x 2 table of cases.rg(u, v) = 1rg(u, v) = 2(parallel directions)(different directions)rg(u, v, AB)= rg(u, v)rg(u, v, AB)= rg(u, v) + 1coincidentranks 1 and 1intersectingranks 2 and 2parallelranks 1 and 2skewranks 2 and 3
The two ranks used by line_position and the four cases. The two zip-line cables go from intersecting to skew when C is raised one metre.

Why it is done this way:

  • nth_roots has no loop: k is a vector and the formula is applied to all its elements. It is MATLAB’s natural style and it is faster.
  • In dist_line, t=AP→⋅u⃗u⃗⋅u⃗t = \frac{\overrightarrow{AP} \cdot \vec u}{\vec u \cdot \vec u} is the projection of AP→\overrightarrow{AP} onto u⃗\vec u (the one from block 2), and Q=A+tu⃗Q = A + t\vec u is its foot. The distance is ∣PQ∣|PQ|.
  • line_position doesn’t solve any system: the two ranks already tell it everything. The lines are coplanar if AB→\overrightarrow{AB} fits in the plane of u⃗\vec u and v⃗\vec v (rank 2) and parallel if u⃗\vec u and v⃗\vec v are proportional (rank 1).

How I would mark it (rough breakdown, my own):

What is assessedPoints
nth_roots without a loop and returning a column1.5
Check with w.^n and a tolerance0.5
dist_line with a projection and two outputs1.5
line_position with two ranks and the four cases1.5

Why dist_line projects instead of using the cross product formula, d=∣AP→×u⃗∣/∣u⃗∣ d = |\overrightarrow{AP} \times \vec u| / |\vec u| : that formula gives the distance, but not the point Q Q , and the function has to return both. With the projection, a single number t t gives you both things. The idea in words: of all the points A+tu⃗ A + t\vec u on the line, the closest one to P P is the one where PQ PQ is perpendicular to the line. Traced with the street lamp from exercise 3:

CommandResultWhy
P - A(20,10,−3) (20, 10, -3) The vector from tree A A to the bulb
dot(P - A, u)1124800 + 300 + 24: how much of that vector goes in the direction of the cable
dot(u, u)2564It is the length of u⃗ \vec u squared: you divide by it so that t t doesn’t depend on how long u⃗ \vec u is
t0.4384Q Q is 43.8 % of the way from A A to B B
Q = A + t*u(17.54, 13.15, 8.49) (17.54,\ 13.15,\ 8.49) You move t t times u⃗ \vec u from A A
d = norm(P - Q)4.0328The length of the perpendicular segment

Since u⃗=B−A \vec u = B – A , t=0 t = 0 is tree A A and t=1 t = 1 is tree B B . With 0.4384, the closest point is on the actual cable; outside [0,1] [0, 1] , 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 C C r2 is also 2: AC→ \overrightarrow{AC} 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 xx and the imaginary part as yy. 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:

Logo starFive-pointed star from the fifth roots of 32.-2-1012-2-1012Logo star
The figure of exercise 3 a): the five circles are the fifth roots of 32 (modulus 2, every 72°) and the star comes from joining every second one.

b) The points are every 72°, so the gap between two points is at 36°: you multiply by ei⋅36°=eiπ/5e^{i \cdot 36°} = e^{i\pi/5}. 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 (402+302+82=2564\sqrt{40^2 + 30^2 + 8^2} = \sqrt{2564}) and passes 4.03 m from the bulb, through the point Q≈(17.54,13.15,8.49)Q \approx (17.54, 13.15, 8.49): 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 CC they are intersecting: the two cables meet. You can see it with half of each: A+12u⃗=(20,15,8)A + \tfrac12\vec u = (20, 15, 8) and C+12v⃗=(20,15,8)C + \tfrac12\vec v = (20, 15, 8), the same point. Raising CC 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 164=2\sqrt[4]{16} = 2, 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 k k is at the angle 72°⋅(k−1) 72° \cdot (k – 1) :

VertexAngleWhy
10°You start at the real number 2
3144°You skip 2: two steps of 72°
5288°Another 144°
272°432°, one full turn plus 72°
4216°Another 144°
10°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: −1=eiπ -1 = e^{i\pi} 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, eiπ/5 e^{i\pi/5} 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.

Question 1Single choice

What does this code print?

z = -3 + 4i;
abs(z)
  1. ans = 5
  2. ans = 1
  3. ans = 3.0000 + 4.0000i
  4. ans = 25
Solution

Answer: ans = 5

abs of a complex number is its modulus, a2+b2\sqrt{a^2 + b^2}.

Question 2Single choice

What does this code print?

z = 2i;
w = z * 1i
  1. w = -2
  2. w = 2
  3. w = 0.0000 + 2.0000i
  4. w = 3i
Solution

Answer: w = -2

Multiplying by ii is a 90° anticlockwise rotation.

Question 3Single choice

What does this code print?

for i = 1:2
end
z = 1 + i
  1. z = 3
  2. z = 1.0000 + 1.0000i
  3. z = 2
  4. An error
Solution

Answer: z = 3

It is snippet 2: write 1i for the imaginary unit and you won’t have this problem.

Question 4Single choice

What does this code print?

k = (0:3)';
size(k)
  1. ans = 4 1
  2. ans = 1 4
  3. ans = 4
  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.

Question 5Multiple · wrong ticks subtract

With u = [1 2 3] and v = [4 5 6] (rows), which commands give the dot product, 32?

  1. dot(u, v)
  2. u * v’
  3. u * v
  4. u .* v
Solution

Answer: dot(u, v) · u * v’

1⋅4+2⋅5+3⋅6=321 \cdot 4 + 2 \cdot 5 + 3 \cdot 6 = 32. sum(u .* v) would also give 32.

Question 6Single choice

What does this code print?

u = [1; 2; 0]; v = [2; 4; 0];
rank([u v])
  1. ans = 1
  2. ans = 2
  3. ans = 3
  4. ans = 0
Solution

Answer: ans = 1

With rank⁡(u⃗,v⃗)=1\operatorname{rank}(\vec u, \vec v) = 1, the lines are parallel or coincident; the second rank decides.

Question 7True or false

About the article’s line_position function:

  1. If both ranks are 2, the lines meet at a point.
  2. If the lines are skew, the second rank is 2.
  3. It needs the points and directions as columns.
  4. 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.

Question 8Single choice

How many elements does nth_roots(16, 4) have with the article’s function, and what is their modulus?

  1. 4 roots of modulus 2
  2. 1 root, 2
  3. 2 roots, ±2
  4. 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.

Question 9Fill in the gaps

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 eiθe^{i\theta} with θ\theta in radians: 45° = π/4\pi/4.

Question 10Single choice

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))
  1. d = 4
  2. d = 5
  3. d = 3
  4. d = 0
Solution

Answer: d = 4

It is dist_line without the function: project AP→\overrightarrow{AP} onto u⃗\vec u, 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:

  1. 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?
  2. Compute nth_roots(-16, 4) and check with size that it is a column.
  3. Find a point CC for the second cable that makes it parallel to the first, and check that line_position detects it.
  4. Draw both cables with plot3([A(1) B(1)], [A(2) B(2)], [A(3) B(3)]) (and another plot3 for the second one, with hold 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 abs inside acosd. 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 k=0k = 0 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.

AG exam coming up?The test and practical packs with new solved questions and exercises, their cheat sheets, a blank test and practical exam and MATLAB functions, for free.See the pack

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…CodeWatch out
A complex numberz = 3 + 4i1i better than i
Modulus and argumentabs(z), angle(z)angle in radians, from −π-\pi to π\pi
In degreesrad2deg(angle(z))
From polar to binomialr*exp(1i*theta)theta in radians
Rotate by θ\thetaz * exp(1i*theta)Modulus 1: the size doesn’t change
nth rootsabs(z)^(1/n)*exp(1i*(angle(z)+2*pi*k)/n)k = (0:n-1)'
Plot complex numbersplot(real(w), imag(w), 'o'), axis equal
Dot productdot(u, v) or u'*v (columns)u*v with two columns gives an error
Element by elementu .* vGives a vector
Cross productcross(u, v)Only in 3D
Point-line distancedist_line(P, A, u)Or norm(cross(P-A, u))/norm(u)
Position of two linesrank([u v]), rank([u v B-A])1 = parallel; 3 = skew
Plot in 3Dplot3(x, y, z)Rotate the figure with the mouse

Templates for the exercises:

  • Roots: common modulus → k as a column → vectorised formula → check w.^n with 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.
SymptomLikely cause
Incorrect dimensions for matrix multiplicationu*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 consistentA function returns a row when you expected a column
The star comes out as a pentagonYou 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 realRounding leftover: compare with a tolerance

Before handing it in, ask yourself:

  1. Have I used 1i and not i for the imaginary unit?
  2. Do my functions return the shape they say (row or column), and have I checked it with size?
  3. Is every product of vectors the one I want: dot, .* or cross?
  4. 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