Vector spaces in MATLAB — exercises to program your own Gram-Schmidt, a projection and the phone bill line (and the basis I failed in lab assignment 3)

In lab assignment 3 of AG (Linear Algebra and Geometry) I got a 5 again, and one of the questions I failed asked for a basis of a subspace given by two implicit equations, with format rat and keeping the fractions. The command that solves it fits in one line, null(A, 'r'), and in this article you’ll use it inside your own functions, together with a Gram-Schmidt you write yourself, with its loops and its tolerances.

How to use this article

The algebra is taken as known: what a basis is, a subspace given by implicit equations, the dot product or a projection are in Vector spaces and Euclidean space. Here you program: for and while loops, if conditions, functions that return several things and, above all, comparing decimal numbers without falling into == 0. The MATLAB pieces are in the theory of this block, MATLAB intensive 2: vector spaces and Euclidean space.

The example running through the article is the phone bill month by month: six months of bills, a line that sums them up and the usual question, when will you go over €30. That line is a projection, and you’ll compute it with your own Gram-Schmidt.

  1. Level 1 (reproduce): Command Window commands on bases, implicit equations and angles, with what comes out.
  2. Level 2 (write the function): your my_gs (Gram-Schmidt) and your project, checked with dot products.
  3. Level 3 (full lab assignment): the bill line step by step, with the questions the assignment quiz would ask.
  4. The solutions are folded. After them come “What is wrong here?” and a 10-question 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.

Level 1: bases, implicit equations and angles

Exercise 1. a) The subspace U⊂R4U \subset \mathbb{R}^4 has the implicit equations x+2y−z+t=0x + 2y – z + t = 0 and 3x−y+2z−2t=03x – y + 2z – 2t = 0. Write the coefficient matrix and the command that gives a basis of UU with the parameters set to 1 and 0. Write it again with format rat and check with a matrix product that the vectors satisfy both equations. b) Compute the cosine and the angle in degrees between u⃗=(1,2,2)\vec u = (1, 2, 2) and v⃗=(2,0,1)\vec v = (2, 0, 1). c) Predict what dot([0.1 0.2 0.3], [3 0 -1]) == 0 returns and then check it.

Expected result: dim⁡U=2\dim U = 2, with basis {(−3/7,5/7,1,0),  (3/7,−5/7,0,1)}\{(-3/7, 5/7, 1, 0),\; (3/7, -5/7, 0, 1)\}; the cosine is 0.5963 and the angle, 53.3957°; the comparison with == 0 gives 0 (false), even though the two vectors are orthogonal.

The number of basis vectors is the number of unknowns minus the rank of the matrix. And in c), do the sum by hand: 0.3−0.30.3 – 0.3… but the computer doesn’t store 0.1 or 0.3 exactly.

Level 2: writing your own Gram-Schmidt and projection

Exercise 2. a) Write a function Q = my_gs(V) that takes some vectors in the columns of V and returns in the columns of Q an orthonormal basis of the subspace they span. If a column depends on the previous ones, the function must skip it and say so with fprintf, without stopping. b) Write [p, c] = project(v, U), which returns the orthogonal projection p of v onto the subspace spanned by the columns of U and the coefficients c of p in those columns. c) Test my_gs with the columns of (110101011)\begin{pmatrix} 1 & 1 & 0 \\ 1 & 0 & 1 \\ 0 & 1 & 1 \end{pmatrix} and check that Q'*Q is the identity; test it also with the columns of (120241001)\begin{pmatrix} 1 & 2 & 0 \\ 2 & 4 & 1 \\ 0 & 0 & 1 \end{pmatrix}.

Expected result: with the first matrix you get three orthonormal columns and Q'*Q is the identity (with the odd 0.0000); with the second, the function warns that column 2 depends on the previous ones and returns only two columns.

The orthonormal basis starts empty, Q = zeros(n, 0), and grows with Q = [Q, w/norm(w)]. From each vector you remove its projection onto each column already in Q. A column “depends” when what is left has an almost-zero norm, not exactly zero.

Level 3: a full lab assignment

As in the lab assignment guides on the campus: each part asks for a command or a short answer, and at the end there are questions like the quiz ones. Use my_gs and project.

Exercise 3. The phone bill line. The bills for the last six months were €12, 15, 14, 18, 20 and 21. We want the line g≈c1+c2⋅monthg \approx c_1 + c_2 \cdot \text{month} that sums them up best.

  • a) Write the vector g of bills (as a column), the column of ones one and the column of months month, and the matrix U = [one month]. With two ranks, justify that g is not in the subspace spanned by the columns of U (that is, that no line goes through the six points).
  • b) Compute with project the projection p of g and its coefficients. What is the line?
  • c) Check that the error r = g - p is orthogonal to both columns of U with a single command and a tolerance.
  • d) What does the line predict for month 7? Write a while loop that moves forward month by month from month 6 until the line goes over €30 and say in which month it happens.
  • e) Quiz questions: (1) True or false: g is a linear combination of the columns of U. (2) Fill in: the projection p is the vector of the subspace ___ to g. (3) What does U \ g return in this system of six equations and two unknowns?

Expected result: ranks 2 and 3; the line is g≈10.27+1.83⋅monthg \approx 10.27 + 1.83 \cdot \text{month}; U'*r comes out around 10−1410^{-14}; the prediction for month 7 is €23.07 and the line goes over €30 in month 11.

The rank of [U g] is 3 if g adds a new direction. In c), U'*r gives both dot products at once (column of ones times r and column of months times r).

What is wrong here?

Snippet 1: the Gram-Schmidt that subtracts the wrong thing

V = [1 1; 1 0; 0 1];
q1 = V(:,1) / norm(V(:,1));
w = V(:,2) - dot(V(:,2), V(:,1)) * V(:,1);
q2 = w / norm(w);
dot(q1, q2)

Output:

ans =

   -0.5000

q1 and q2 should be orthogonal and their dot product is not zero. It subtracts the projection onto the original vector V(:,1), which doesn’t have norm 1: the formula ⟨v⃗,q⃗⟩ q⃗\langle \vec v, \vec q\rangle\,\vec q only works with a unit q⃗\vec q. Since V(:,1) measures 2\sqrt 2, it subtracts twice as much as it should.

Using the original vector instead of the normalised one. Either divide by the squared norm, ⟨v⃗,u⃗⟩⟨u⃗,u⃗⟩u⃗\frac{\langle \vec v, \vec u\rangle}{\langle \vec u, \vec u\rangle}\vec u, or use q1, which is already a unit vector.

w = V(:,2) - dot(V(:,2), q1) * q1;
q2 = w / norm(w);
dot(q1, q2)

Output:

ans =

   1.1102e-16

Now it comes out as 1.1⋅10−161.1 \cdot 10^{-16}: zero, apart from the usual rounding. That is why the orthogonality check is never done with == 0, as you’ll see in snippet 2.

Snippet 2: two orthogonal vectors that “aren’t”

w = [0.1 0.2 0.3]; z = [3 0 -1];
if dot(w, z) == 0
  disp('They are orthogonal')
else
  disp('They are not orthogonal')
end

Output:

They are not orthogonal

By hand, 0.3+0−0.3=00.3 + 0 – 0.3 = 0. On the computer, 0.1 and 0.3 aren’t stored exactly, and the dot product comes out as 5.55⋅10−175.55 \cdot 10^{-17}: almost zero, but not zero.

dot(w, z)

Output:

ans =

   5.5511e-17

Comparing with == 0 a number that comes out of decimal arithmetic. Compare with a tolerance: abs(dot(w, z)) < 1e-10. With small integer vectors it doesn’t happen, which is why the bug shows up precisely with real data.

if abs(dot(w, z)) < 1e-10
  disp('They are orthogonal')
end

Output:

They are orthogonal

Snippet 3: the while that never ends

month = 6; cost = 21;
while cost <= 30
  cost = 10.27 + 1.83 * month;
end

Output:

Execution stopped: too many steps (is there a loop that never ends?).

In MATLAB this keeps thinking forever (you stop it with Ctrl + C); the website’s environment cuts it off and tells you. The condition depends on cost, cost depends on month… and month never changes inside the loop: every iteration computes the same number.

Before writing a while, ask yourself which variable in the condition changes in each iteration. If none does, the loop can’t end. Here month = month + 1; is missing.

Solutions

Exercise 1

Before you open the solution, the plan. In a) you are not asked to solve a system by hand, but to translate it: the vectors of U U are exactly the ones that satisfy Ax⃗=0⃗ A\vec x = \vec 0 , so its basis is the basis of the null space of the coefficient matrix. That is why the command is null, and not solving for the unknowns. What decides which basis comes out is the ‘r’: MATLAB row-reduces the matrix and gives one vector per free parameter, with that parameter set to 1 and the others to 0. This is the row reduction it does inside:

A = [1 2 -1 1; 3 -1 2 -2];
format rat
R = rref(A)

Output:

R =

       1              0              3/7           -3/7     
       0              1             -5/7            5/7     

Read it row by row: x+37z−37t=0 x + \tfrac{3}{7}z – \tfrac{3}{7}t = 0 and y−57z+57t=0 y – \tfrac{5}{7}z + \tfrac{5}{7}t = 0 . The columns of z z and t t have no pivot: they are the parameters. With z=1,t=0 z = 1, t = 0 you get x=−3/7 x = -3/7 , y=5/7 y = 5/7 , the first vector of the basis; with z=0,t=1 z = 0, t = 1 , the second one.

Show the solution to exercise 1

a)

A = [1 2 -1 1; 3 -1 2 -2];
B = null(A, 'r')
format rat
B
format short
A * B

Output:

B =

   -0.4286    0.4286
    0.7143   -0.7143
    1.0000         0
         0    1.0000

B =

      -3/7            3/7     
       5/7           -5/7     
       1              0       
       0              1       

ans =

   1.0e-16 *

   -2.2204    2.2204
         0         0

Rank 2 and four unknowns: the basis has 4−2=24 – 2 = 2 vectors, with zz and tt as parameters (hence the 1 and 0 in the last two rows). With format rat you read −3/7,5/7-3/7, 5/7 and 3/7,−5/73/7, -5/7. And A*B gives the zero matrix: each column of B satisfies both equations. Notice it comes out here with a 1.0e-16 factor: rounding leftovers, the same story as snippet 2.

b)

u = [1 2 2]; v = [2 0 1];
co = dot(u, v) / (norm(u) * norm(v))
ang = acosd(co)

Output:

co =

    0.5963

ang =

   53.3957

By hand: ⟨u⃗,v⃗⟩=2+0+2=4\langle \vec u, \vec v\rangle = 2 + 0 + 2 = 4, ∥u⃗∥=3\|\vec u\| = 3, ∥v⃗∥=5\|\vec v\| = \sqrt 5, and cos⁡α=4/(35)≈0.5963\cos\alpha = 4/(3\sqrt5) \approx 0.5963. acosd gives the angle in degrees directly; with acos it would come out in radians.

c)

dot([0.1 0.2 0.3], [3 0 -1]) == 0

Output:

ans =

  logical

   0

It gives 0 (false). It is snippet 2 in miniature.

Why it is done this way: the name co and not cosd, because cosd is a MATLAB function (the cosine in degrees) and naming a variable like that hides it until you clear it. And null(A, 'r'), not null(A): without the 'r' you get an orthonormal basis with decimals, which is valid but not the one a quiz with fractions asks for.

Exercise 2

The plan for my_gs, before writing a single line. There are three decisions:

  • Where what you have built is kept. Q starts with zero columns and grows, so “the q’s already built” are always the columns of Q, and the inner loop runs over 1:size(Q, 2), which does no turns at all the first time.
  • What is done to each column. Remove its part along each q already built: only with respect to the columns of Q, which are already orthonormal, not the columns of V.
  • When a column is skipped. When what is left is almost zero. The obvious path, norm(w) == 0, fails for the same reason as snippet 2.
Show the solution to exercise 2
function Q = my_gs(V)
  % Gram-Schmidt: orthonormal basis (in columns) of the span of the columns of V.
  Q = zeros(size(V, 1), 0);              % starts with no columns
  for j = 1:size(V, 2)
    w = V(:, j);
    for k = 1:size(Q, 2)
      w = w - dot(w, Q(:, k)) * Q(:, k);  % remove its part along each q already built
    end
    if norm(w) < 1e-10                    % almost zero: it depended on the previous ones
      fprintf('Column %d depends on the previous ones: skipping it.\n', j);
      continue
    end
    Q = [Q, w / norm(w)];                 % normalise it and add it
  end
end

function [p, c] = project(v, U)
  % Orthogonal projection of v onto the span of the columns of U,
  % and its coefficients in those columns.
  Q = my_gs(U);
  p = Q * (Q' * v);                       % sum of <v, q_k> q_k
  c = U \ p;                              % p is in the subspace: exact solution
end
Q = my_gs([1 1 0; 1 0 1; 0 1 1])
Q' * Q
Q2 = my_gs([1 2 0; 2 4 1; 0 0 1])

Output:

Q =

    0.7071    0.4082   -0.5774
    0.7071   -0.4082    0.5774
         0    0.8165    0.5774

ans =

    1.0000    0.0000    0.0000
    0.0000    1.0000    0.0000
    0.0000    0.0000    1.0000

Column 2 depends on the previous ones: skipping it.

Q2 =

    0.4472   -0.3651
    0.8944    0.1826
         0    0.9129

Q'*Q is the matrix of all the dot products between the columns of Q: ones on the diagonal (each column has length 1) and zeros elsewhere (they are orthogonal). The 0.0000 are, again, leftovers of 10−1610^{-16}. With the second matrix, the column (2,4,0)(2, 4, 0) is twice the first: after removing its projection the zero vector is left, the function detects it, says so and carries on.

The picture shows what one pass of the inner loop does: each vector loses its shadow on every direction already in Q.

Gram-Schmidt: removing the projectionv, its projection on q1 and the remainder w.q₁v⟨v, q₁⟩ q₁ww = v − ⟨v, q₁⟩ q₁w is perpendicular to q₁q₂ = w / ‖w‖If ‖w‖ ≈ 0, v was alongq₁: it is skipped
One pass of the inner loop of mi_gs: v loses its shadow on q₁ (in coral) and what is left, w, is perpendicular to q₁.

Why it is done this way:

  • w = w - dot(w, Q(:,k)) * Q(:,k) uses the w that has already been cleaned up (modified Gram-Schmidt), not the original vector. On paper it makes no difference; on the computer it builds up less error.
  • continue instead of error: a dependent vector isn’t the user’s fault, it just adds nothing. The function goes on with the others.
  • In project, Q * (Q' * v) does ∑k⟨v⃗,q⃗k⟩q⃗k\sum_k \langle \vec v, \vec q_k\rangle \vec q_k in one go: Q'*v are the dot products and Q* uses them as coefficients.
  • c = U \ p works because p is in the subspace: that system is consistent and \ gives the exact solution.

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

What is assessedPoints
Double loop: one pass per column and another per q already built1.5
Normalise and add columns to Q0.5
Dependent columns with a tolerance, a message and continue1
project with two outputs1
Check with Q'*Q1

The second matrix, turn by turn, since it is the one with the catch:

jw at the startI removew at the endWhy
1(1, 2, 0)nothing(1, 2, 0)Q is empty; it is normalised and q1 = (0.4472, 0.8944, 0)
2(2, 4, 0)4.4721 · q1(0, 0, 0)it is twice the first one: it was all shadow on q1, so it warns and continues
3(0, 1, 1)0.8944 · q1(-0.4, 0.2, 1)its length is 1.2≈1.0954 \sqrt{1.2} \approx 1.0954 , far from zero: it is normalised

Why orthonormalise before projecting? Because the obvious path, projecting onto each column of U separately and adding up, only works if those columns are orthogonal. The ones in exercise 3 are not:

g = [12; 15; 14; 18; 20; 21]; one = ones(6, 1); month = (1:6)';
dot(one, month)
p_wrong = dot(g, one)/dot(one, one) * one + dot(g, month)/dot(month, month) * month;
U = [one month];
p_right = U * (U \ g);
[p_wrong p_right]

Output:

ans =

    21

ans =

   20.8645   12.0952
   25.0623   13.9238
   29.2601   15.7524
   33.4579   17.5810
   37.6557   19.4095
   41.8535   21.2381

The dot product of the two columns is 21, not 0, and the left column reaches almost €42 in month 6, when the bill was €21: the two shadows overlap, because each one already carries a piece of the other. Gram-Schmidt removes that overlap before adding up.

Exercise 3

The plan: each part is a question about bills that has to be translated into algebra (the “best line” is not new statistics, it is the projection from exercise 2):

What is askedTranslatedTool
Is there a line through the six points?Is g in the subspace of one and month?rank(U) against rank([U g])
Which line sums them up best?Which vector of the subspace is closest to g?project
Is it really the best?Is the error perpendicular to the subspace?U’*r with a tolerance
When will I go over €30?First month with c1+c2⋅month>30 c_1 + c_2 \cdot \text{month} > 30 ?a while that moves m forward
Show the solution to exercise 3

a)

g = [12; 15; 14; 18; 20; 21];
one = ones(6, 1); month = (1:6)';
U = [one month];
rank(U), rank([U g])

Output:

ans =

     2

ans =

     3

The rank goes up from 2 to 3: g is not a linear combination of the columns of U. In plain words: no line goes through the six points.

b)

[p, c] = project(g, U)

Output:

p =

   12.0952
   13.9238
   15.7524
   17.5810
   19.4095
   21.2381

c =

   10.2667
    1.8286

The line is g≈10.27+1.83⋅monthg \approx 10.27 + 1.83 \cdot \text{month}: about €10 fixed and almost €2 more each month. p are the values of the line in months 1 to 6.

c)

r = g - p;
U' * r
all(abs(U' * r) < 1e-10)

Output:

ans =

   1.0e-14 *

   -2.1316
    2.6645

ans =

  logical

   1

Both dot products are around 10−1410^{-14} and the check with a tolerance gives 1. The error is perpendicular to the subspace: that is what makes p the orthogonal projection, and that is why this line is the least squares line.

The picture shows the six months, the line and, for each month, the piece of error r that the projection makes as small as possible.

The phone bill lineBill points, fitted line and errors.10 €15 €20 €25 €1234567month€23.07g ≈ 10.27 + 1.83 · monthin coral: the error r = g − p
The six bills (dots), the line that comes from the projection and the prediction for month 7. The coral segments are the error r: the projection makes their total squared length as small as possible.

d)

c(1) + c(2)*7
m = 6;
while c(1) + c(2)*m <= 30
  m = m + 1;
end
m

Output:

ans =

   23.0667

m =

    11

For month 7, €23.07. The loop starts at month 6 and moves forward while the line doesn’t go over 30; it stops at 11 (check: 10.27+1.83⋅11≈30.3810.27 + 1.83 \cdot 11 \approx 30.38, and in month 10 it was 28.55).

e) (1) False: the rank of [U g] is 3. (2) Closest: ∥g⃗−p⃗∥\|\vec g – \vec p\| is the shortest distance from g⃗\vec g to the subspace. (3) With more equations than unknowns, U \ g returns the least squares solution, the same coefficients as in b): that is what you get if you type U \ g directly.

Why it is done this way: in a) the ranks are used, not “let’s see whether U\g gives something”, because U\g always returns a number, even when there is no exact solution. And in d) the while changes m inside the loop, exactly what snippet 3 was missing.

The while in d), turn by turn:

mLine at mDoes it go on?Why
621.24yesnot over 30: m goes up to 7
7 to 923.07 · 24.90 · 26.72yeseach turn adds c2≈1.83 c_2 \approx 1.83 euros
1028.55yes€1.45 still to go
1130.38nothe condition is false: the loop stops with m = 11

It comes out as 11 and not 10 because the while stops at the first month that does not meet the condition, and that is exactly the one that goes over 30. The obvious path would have been to solve for m: c1+c2⋅m>30 c_1 + c_2 \cdot m > 30 gives m>(30−c1)/c2≈10.79 m > (30 – c_1)/c_2 \approx 10.79 , and the first whole number is 11. It matches, but solving only works for a line; the loop works for any formula.

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?

V = [1 2; 2 4; 0 1];
rank(V) == size(V, 2)
  1. ans = logical 1
  2. ans = logical 0
  3. ans = 2
  4. An error, because V is not square
Solution

Answer: ans = logical 1

The columns are (1, 2, 0) and (2, 4, 1): the third component breaks the proportion. Rank 2 with 2 columns: independent.

Question 2Single choice

What does this code print?

t = 0;
k = 1;
while t < 10
  t = t + k;
  k = k + 1;
end
k
  1. k = 5
  2. k = 4
  3. k = 10
  4. It never ends
Solution

Answer: k = 5

Iteration by iteration: t = 1, 3, 6, 10 and k = 2, 3, 4, 5. With t = 10 the condition t < 10 is false and the loop ends with k = 5.

Question 3Single choice

What does this code print?

x = 0.1 + 0.2;
disp(x == 0.3)
disp(abs(x - 0.3) < 1e-10)
  1. 0 and then 1
  2. 1 and then 1
  3. 0 and then 0
  4. 1 and then 0
Solution

Answer: 0 and then 1

It is the same problem as with the dot products in snippet 2: decimals are compared with a tolerance.

Question 4Single choice

If A is a 2 × 5 matrix of rank 2, how many columns does null(A, 'r') have?

  1. 3
  2. 2
  3. 5
  4. 7
Solution

Answer: 3

The basis of the kernel has as many vectors as free parameters: n−rank⁡(A)=5−2=3n – \operatorname{rank}(A) = 5 – 2 = 3.

Question 5Single choice

What does this code print?

u = [3; 4];
q = u / norm(u)
  1. q = [0.6000; 0.8000]
  2. q = [3; 4]
  3. q = 5
  4. q = [0.7500; 1.3333]
Solution

Answer: q = [0.6000; 0.8000]

∥(3,4)∥=9+16=5\|(3, 4)\| = \sqrt{9 + 16} = 5 and q⃗=(3/5,4/5)\vec q = (3/5, 4/5), a unit vector.

Question 6True or false

About the article’s my_gs function:

  1. If two columns of V are proportional, Q has fewer columns than V.
  2. Q always has the same number of columns as V.
  3. Q’*Q is the identity apart from rounding leftovers.
  4. Q*Q’ is always the identity.
Solution
  • T — If two columns of V are proportional, Q has fewer columns than V.
  • F — Q always has the same number of columns as V.
  • T — Q’*Q is the identity apart from rounding leftovers.
  • F — Q*Q’ is always the identity.

Q'*Q compares the columns with each other (orthonormal: identity). Q*Q' is the matrix of the projection onto the subspace, and it is only the identity if the subspace is the whole space.

Question 7Single choice

What does this code print?

S = [1 2 1; 2 4 0; 0 0 1];
[~, piv] = rref(S);
piv
  1. piv = 1 3
  2. piv = 1 2 3
  3. piv = 1 2
  4. piv = 2
Solution

Answer: piv = 1 3

The second output of rref tells you which columns have a pivot. S(:, piv) would be columns 1 and 3, which form a basis with original vectors.

Question 8Fill in the gaps

Complete the projection of v onto the span of the columns of Q (orthonormal):

p = ____ * (____ * v);

Words:

  • Q
  • Q*Q
  • inv(Q)
  • Q'
  • v
Solution

p = Q * (Q’ * v);

Q'*v gives the dot products ⟨v⃗,q⃗k⟩\langle \vec v, \vec q_k\rangle and Q* uses them as the coefficients of the combination.

Question 9Single choice

What does this code print?

G = [2 0; 0 1];
u = [1; 1]; v = [1; -2];
u' * G * v
  1. ans = 0
  2. ans = -1
  3. ans = 4
  4. A dimensions error
Solution

Answer: ans = 0

With the Gram matrix, ⟨u⃗,v⃗⟩=u⃗tGv⃗=2u1v1+u2v2\langle \vec u, \vec v\rangle = \vec u^t G \vec v = 2u_1v_1 + u_2v_2. Orthogonal with one dot product doesn’t mean orthogonal with another.

Question 10Multiple · wrong ticks subtract

Which of these loops end?

  1. k = 1; while k < 5, k = k * 2; end
  2. for k = 1:1000, end
  3. k = 0; while k ~= 1, k = k + 0.3; end
  4. k = 5; while k > 0, k = k + 1; end
Solution

Answer: k = 1; while k < 5, k = k * 2; end · for k = 1:1000, end

A while ends if what changes inside eventually makes the condition false. With decimals and ~=, it may never hit the exact value.

Try it in the MATLAB environment

Open the MATLAB environment, paste the script of exercise 3 and, at the end, my_gs and project. Then:

  1. Change the bills to yours and see in which month you would go over €30.
  2. Add a third column month.^2 to U: the projection is no longer a line but a parabola. Does norm(g - p) go down?
  3. Call my_gs with magic(4): it has rank 3, so one column has to be skipped.
  4. Remove the tolerance from my_gs (if norm(w) == 0) and call it again with the repeated-column matrix: you’ll see an “almost zero” vector normalised into a meaningless direction.

For your lab assignments

Lab assignment 3 on the campus asks for bases of subspaces, implicit equations, the sum of subspaces and angles with a dot product given by a Gram matrix. This model script does all of that with the functions at the end; change only the data at the top.

%% Subspaces and dot product: template for lab assignment 3
format short
A  = [1 2 -1 1; 3 -1 2 -2];   % implicit equations of U (one row per equation)
S1 = [1 0; 2 1; 0 1; 1 1];    % spanning set of U1 (in columns)
S2 = [1 0; 3 1; 1 1; 2 0];    % spanning set of U2 (in columns)
G  = [2 1 0; 1 2 0; 0 0 1];   % Gram matrix of a dot product on R^3

%% 1. Basis of U from its implicit equations (with fractions)
format rat
BU = null(A, 'r')
format short

%% 2. Basis of U1 + U2 with original vectors
BS = original_basis([S1 S2])

%% 3. Cosine and angle with the Gram matrix
[co, ang] = gram_angle([1; 0; 1], [0; 1; 1], G)

%% ---- functions (always at the end) ----
function B = original_basis(S)
  % Columns of S that form a basis of the subspace they span:
  % the ones with a pivot in the reduced row echelon form.
  [~, piv] = rref(S);
  B = S(:, piv);
end

function [co, ang] = gram_angle(u, v, G)
  % Cosine and angle (in degrees) between u and v with the dot product u'*G*v.
  co  = (u' * G * v) / (sqrt(u' * G * u) * sqrt(v' * G * v));
  ang = acosd(co);
end

Output:

BU =

      -3/7            3/7     
       5/7           -5/7     
       1              0       
       0              1       

BS =

     1     0     0
     2     1     1
     0     1     1
     1     1     0

co =

    0.6667

ang =

   48.1897

What this script saves you in the quiz:

  • Original vectors: here the first column of S2 is the sum of the two in S1, so it is redundant and BS keeps three. [~, piv] = rref(S) returns in its second output the columns with a pivot, and S(:, piv) takes those original vectors, not the ones from the echelon form. It is the most failed question of this assignment.
  • The dot product with Gram is always u'*G*v, with u and v as columns. The function gram_angle doesn’t need to know whether G is the identity or not.
  • Four decimals: the quiz compares with what format short shows. Copy the number as it comes out, without rounding it yourself.

What next?

If the loops or the functions with two outputs were hard, review the theory of this block, MATLAB intensive 2: vector spaces and Euclidean space. And the previous block, matrices and systems, has the my_gj you can use to decide dependencies by hand.

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: vector spaces in MATLAB

The essentials in 30 seconds: independence and membership are decided with rank; implicit equations are solved with null(A, 'r'); dot products are dot(u, v) or u'*G*v; and no decimal number is compared with ==, always with a tolerance.

I want…CodeWatch out
Independent?rank(V) == size(V, 2)Vectors in columns
Is v in the subspace?rank([V v]) == rank(V)If it goes up, it isn’t
Basis from implicit equationsnull(A, 'r')Without 'r', an orthonormal basis with decimals
Basis with original vectors[~, piv] = rref(S); S(:, piv)Not the columns of the reduced form
Dot productdot(u, v) or u'*G*vWith Gram, vectors as columns
Angle in degreesacosd(co)acos gives radians
Orthonormalisemy_gs(V)orth(V) gives another valid basis
ProjectionQ*(Q'*v) with orthonormal QOr U \ v for the coefficients
Almost zero?abs(x) < 1e-10, norm(w) < 1e-10Never == 0 with decimals
Loop until something happenswhile cond ... endSomething in cond must change inside

Templates for the exercises:

  • Gram-Schmidt: empty Q → for each column, subtract its projection on each q → if the norm is almost zero, skip → normalise and add.
  • Projection and line: U with the column of ones and the variable → ranks to see if there is an exact solution → project → orthogonal error with U'*r.
  • Search loop: starting value → while with the opposite of the condition you are looking for → update inside → read the variable when it ends.
SymptomLikely cause
Q'*Q is not the identityYou subtract the projection onto a non-unit vector
“Not orthogonal” for orthogonal vectorsYou compare with == 0
A basis with odd decimals (0.4472…)null(A) without the 'r'
cosd stops workingYou called a variable cosd
The program doesn’t endThe while changes nothing in its condition
Dimensions ... not consistent in u'*G*vu or v as a row

Before handing it in, ask yourself:

  1. Have I decided every dependency or membership with ranks, not by eye?
  2. Do all comparisons of decimal numbers have a tolerance?
  3. Are the basis vectors the original ones when the question asks for that?
  4. Have I copied the decimals exactly as format short shows them?

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

Block theory: Loops, bases, Gram-Schmidt and projectionVector spaces in MATLABCheat sheet: the block on one page, to reviewCheat sheetLab assignments: the block's functions and a model scriptFor your lab assignments