Vector spaces in MATLAB — theory for programming with loops: bases that pick themselves, your own Gram-Schmidt and projection as a function (and the recipe that added nothing)

One Sunday in the flat I found out that one of our recipes was the sum of two others: Pablo’s “Cuban rice with omelette” was the Cuban rice plus the cheese omelette. I saw it when I wrote the recipes as vectors for AG lab assignment 3 and computed the rank by hand, column by column. It took me twenty minutes. With a six-line loop, MATLAB does it in the blink of an eye, and it also tells you which one is redundant.

This article is block 2 of the MATLAB programming intensive course and it is about loops: for when you know how many passes there are, while when you do not, if, break and continue, logical vectors for picking columns, and vectors that grow inside a loop. With that we will program a function that picks a basis from a set of vectors, your own Gram-Schmidt and the orthogonal projection as a function, and we will learn to compare results with tolerances instead of ==. We take the algebra as read: it is in vector spaces and subspaces and in Euclidean space. If you are missing how to write a function, start with block 1.

In a nutshell: in MATLAB, for k = 1:n repeats a block a fixed number of times and while condition repeats it while the condition holds. With loops you program linear algebra algorithms such as Gram-Schmidt, which turns some vectors into an orthonormal basis, and the results are checked with tolerances (norm(Q'*Q - eye(k)) < 1e-10) because decimals hardly ever come out exact.

Before you start. For this article you only need to know how to write a function in MATLAB (block 1) and how to take a column out of a matrix with R(:, j). From the algebra, four ideas: what a linear combination is, what the rank measures, the dot product and the norm. Nothing else. The article has two parts: first the pieces of the language (for, a vector that grows, if with logical vectors, while and tolerances); then three programs that put them together, each one built on the previous one: basis_of, gram_schmidt and project. If you get lost, go back to the four recipes: the whole article asks questions about them.

What you will program and for which topic

Each recipe in the flat is a vector with the servings of four ingredients: rice, egg, tomato and cheese.

RecipeRiceEggTomatoCheese
r1\mathbf{r}_1 Cuban-style rice2110
r2\mathbf{r}_2 Cheese omelette0301
r3\mathbf{r}_3 Rice with tomato and cheese2011
r4\mathbf{r}_4 Cuban rice with omelette2411

Put as columns they form a 4×44 \times 4 matrix RR. The questions of AG topics 3 and 4 turn into programs:

  • Are they independent? Which ones form a basis of the space they span? (Topic 3.)
  • Which combination of recipes gives exactly r4\mathbf{r}_4? (Topic 3: the null space.)
  • If I want a week with 3 of rice, 3 of egg, 2 of tomato and 2 of cheese and there is no exact combination, which one is the closest? (Topic 4: the orthogonal projection.)

Today’s functions (basis_of, gram_schmidt and project) work for any set of vectors, of any size.

for: when you know how many passes there are

A for goes through the elements of a vector, one per pass:

R = [2 0 2 2; 1 3 0 4; 1 0 1 1; 0 1 1 1];   % the recipes, as columns
for j = 1:size(R, 2)
    fprintf('Recipe %d: %d servings in total\n', j, sum(R(:, j)));
end

Output:

Recipe 1: 4 servings in total
Recipe 2: 4 servings in total
Recipe 3: 4 servings in total
Recipe 4: 8 servings in total

1:size(R, 2) is 1:4, so the body is repeated four times with j = 1, 2, 3 and 4. fprintf writes with a format: %d is a slot for an integer and \n is a line break. Checking by hand: recipe 4 adds up to 2+4+1+1=82 + 4 + 1 + 1 = 8.

The same loop, pass by pass. Notice that you do not change j yourself: the for gives it the next value of 1:4 at the start of each pass.

PassjR(:, j)sum(R(:, j))Why
11(2,1,1,0) (2, 1, 1, 0) 41:4 starts at 1: the first column, the Cuban rice
22(0,3,0,1) (0, 3, 0, 1) 4the body is the same; only j changes
33(2,0,1,1) (2, 0, 1, 1) 4same again: another column, the same sum
44(2,4,1,1) (2, 4, 1, 1) 8last value of 1:4: there are no more and the loop ends

When it finishes, j still exists and is 4, the last value it took. It seems not to matter, and the box below explains why it does.

Two details that save trouble:

  • The vector in the for can be anything: for j = [4 1 3] goes in that order and for j = 10:-2:4 counts down (10, 8, 6, 4).
  • If you give the for a matrix, it goes through its columns: for r = R makes four passes, and in each one r is a whole recipe (a column vector). It is very handy with vectors stored as columns, as here.

Using i or j as the loop variable and later writing a complex number like 2 + 3i without the 1. After for i = 1:3, i is 3, and 2 + 3*i gives 11, not a complex number. You will see it in block 4: always write 1i.

A vector that grows inside the loop

Often you do not know in advance how many results you will store. You start with an empty vector and append at the end with end+1:

big = [];                         % the recipes with more than 6 servings go here
for j = 1:size(R, 2)
    if sum(R(:, j)) > 6
        big(end+1) = j;           % it grows by one position
    end
end
big

Output:

big =

     4

Only recipe 4 (8 servings) goes over 6. With matrices it is the same, adding columns: B(:, end+1) = v. If you know the final size, it is better to reserve it first with zeros(n, 1) and fill it by position; in big programs, growing a vector pass by pass is slow.

if, elseif, else and logical vectors

A comparison between vectors gives a logical vector: a 1 where it holds and a 0 where it does not. It works as the condition of an if and, above all, as an index to keep the elements that satisfy something:

pantry = [10; 6; 5; 3];           % servings left: rice, egg, tomato, cheese
r2 = R(:, 2);                     % the cheese omelette
enough = pantry >= r2             % is there enough of each ingredient?
if all(enough)
    disp('There is enough for a cheese omelette')
else
    disp('Something is missing')
end

Output:

enough =

  4×1 logical array

   1
   1
   1
   1

There is enough for a cheese omelette

pantry >= r2 compares element by element and returns a 4×1 logical array. all says whether they are all 1 and any, whether there is at least one. An if with a whole vector requires the condition to hold in every element, the same as all, but writing all makes the intention clear.

To pick columns with a logical vector:

chosen = false(1, 4);             % none, to start with
chosen([1 3]) = true;             % the Cuban rice and the rice with tomato
R(:, chosen)

Output:

ans =

     2     2
     1     0
     1     1
     0     1

false(1, 4) creates four logical zeros. Putting a true in positions 1 and 3, R(:, chosen) keeps those two columns. It is how you mark “this one yes, this one no” inside a loop and pull them out at the end.

while: when you do not know how many passes

while condition ... end repeats while the condition is true. How many times can we cook Cuban-style rice with what is in the pantry?

left = pantry;
r1 = R(:, 1);
servings = 0;
while all(left >= r1)             % while there is enough of each ingredient
    left = left - r1;
    servings = servings + 1;
end
servings
left'

Output:

servings =

     5

ans =

     0     1     0     3

Five times: the rice (10 servings, 2 per dish) and the tomato (5, 1 per dish) run out at the same time. There is 1 egg and 3 cheese left. You could not write it with a for, because the number of passes is exactly what we wanted to know.

The while count, without skipping anything. In each pass the first thing is the condition’s question; only if the answer is yes does it cook:

Passleft beforeall(left >= r1)?left afterservingsWhy
1(10,6,5,3) (10, 6, 5, 3) yes(8,5,4,3) (8, 5, 4, 3) 1there is plenty of everything; it subtracts 2, 1, 1 and 0
2(8,5,4,3) (8, 5, 4, 3) yes(6,4,3,3) (6, 4, 3, 3) 2the cheese does not go down: the Cuban rice has none
3(6,4,3,3) (6, 4, 3, 3) yes(4,3,2,3) (4, 3, 2, 3) 3there is still enough of each ingredient
4(4,3,2,3) (4, 3, 2, 3) yes(2,2,1,3) (2, 2, 1, 3) 4still enough for another dish
5(2,2,1,3) (2, 2, 1, 3) yes(0,1,0,3) (0, 1, 0, 3) 5the last possible dish: rice and tomato go down to 0
(6)(0,1,0,3) (0, 1, 0, 3) nonot run50 rice is not enough for 2: the condition is false and the loop ends

The sixth row is the one people forget most: the while asks one more time than it cooks, and that last question comes out no. That is why servings ends at 5 and not at 6.

Check you’ve got it: how many cheese omelettes can you make from the same pantry, and what is left?

Two, and there are 10 rice, 0 egg, 5 tomato and 1 cheese left. Step by step: the omelette is r2=(0,3,0,1) \mathbf{r}_2 = (0, 3, 0, 1) . You start with (10,6,5,3) (10, 6, 5, 3) ; there is enough, and (10,3,5,2) (10, 3, 5, 2) is left. There is enough again (exactly 3 eggs), and (10,0,5,1) (10, 0, 5, 1) is left. On the third question, 0 eggs are not enough for 3: false, and the loop ends with servings = 2. This time the egg decides, not the rice: what stops the loop depends on the recipe.

A while whose condition never stops holding, for example because you forgot left = left - r1. MATLAB does not warn you: it stays busy (“Busy” at the bottom left) until you press Ctrl+C in the Command Window. Before running a while, check that something inside brings the condition closer to being false.

break cuts the loop on the spot and continue jumps to the next pass; they work the same in for and in while. You will see them in Gram-Schmidt.

Tolerances: why == is hardly ever used

You saw it in block 1 and here it is the law, because Gram-Schmidt and the projection divide by norms and take square roots:

0.1 + 0.2 == 0.3
abs((0.1 + 0.2) - 0.3) < 1e-12

Output:

ans =

  logical

   0

ans =

  logical

   1

0.1 and 0.2 cannot be stored exactly in binary, and their sum ends up 5.55⋅10−175.55 \cdot 10^{-17} away from 0.3. That is why “are they equal?” is programmed as “is their difference smaller than a tolerance?”. With vectors and matrices you use the norm of the difference: norm(u - v) < tol. The tolerance depends on the problem; for data like today’s, 1e-10 is plenty.

The full program: from the basis by hand to the projection

Step 1: picking a basis with a loop

The idea from topic 3: I go through the recipes one by one and keep the one that raises the rank of what I already have; if it does not raise it, it is a combination of the previous ones and adds nothing.

Before writing any code, do it yourself with the four recipes. The question at each step is always the same: can this recipe be cooked by mixing the ones I have already kept?

  • r1=(2,1,1,0) \mathbf{r}_1 = (2, 1, 1, 0) : I do not have any yet, and it is not the zero vector. I keep it.
  • r2=(0,3,0,1) \mathbf{r}_2 = (0, 3, 0, 1) : is it a multiple of the Cuban rice? The Cuban rice has 2 rice and the omelette 0, so the only multiple with 0 rice would be 0 times the Cuban rice, all zeros. But the omelette has 3 eggs. It is not a multiple: I keep it.
  • r3=(2,0,1,1) \mathbf{r}_3 = (2, 0, 1, 1) : is it a r1+b r2 a\,\mathbf{r}_1 + b\,\mathbf{r}_2 ? The rice says 2a=2 2a = 2 , so a=1 a = 1 . The egg says a+3b=0 a + 3b = 0 , so b=−1/3 b = -1/3 . But the cheese says b=1 b = 1 . It cannot be both at once: it cannot be made from the previous ones. I keep it.
  • r4=(2,4,1,1) \mathbf{r}_4 = (2, 4, 1, 1) : try the Cuban rice plus the omelette: (2,1,1,0)+(0,3,0,1)=(2,4,1,1) (2, 1, 1, 0) + (0, 3, 0, 1) = (2, 4, 1, 1) . It comes out exactly. It is redundant.

Each “I keep it” is the rank going up by one, and each “redundant”, the rank staying the same. That is exactly what the program is going to check: instead of setting up equations by hand for each recipe, it asks rank whether the new column brings a direction the previous ones did not have.

Thinking the redundant one is “the fourth”. The redundant one is the one that arrives when you already have what it takes to build it; in another order a different one may be redundant. What does not change is how many are kept.

The naive version is a script that does it column by column, by eye:

rank(R(:, 1))
rank(R(:, [1 2]))
rank(R(:, [1 2 3]))
rank(R)

Output:

ans =

     1

ans =

     2

ans =

     3

ans =

     3

The rank goes from 1 to 2 and to 3, and with the fourth recipe it stays at 3: r4\mathbf{r}_4 is redundant. It works, but with 20 recipes it is 20 lines, and you draw the conclusion yourself by looking. The loop version does both things by itself:

function [B, picked] = basis_of(V)
% BASIS_OF  Columns of V that form a basis of the space they span.
%   [B, picked] = basis_of(V): goes through the columns and keeps those that raise the rank.
B = zeros(size(V, 1), 0);        % a matrix with no columns, with the rows of V
picked = [];
for j = 1:size(V, 2)
    candidate = [B V(:, j)];     % what I have plus column j
    if rank(candidate) > size(B, 2)
        B = candidate;           % it adds something: it stays
        picked(end+1) = j;
    end
end
end

With the four recipes:

[B, picked] = basis_of(R)
dimension = size(B, 2)

Output:

B =

     2     0     2
     1     3     0
     1     0     1
     0     1     1

picked =

     1     2     3

dimension =

     3
basis_of keeps the columns that raise the rankFour recipe vectors as columns; after r1, r2 and r3 the rank is 1, 2 and 3, so they stay; with r4 it stays at 3 because r4 equals r1 plus r2.r1Cuban rice2110rank 1staysr2Cheese omelette0301rank 2staysr3Rice, tomato, cheese2011rank 3staysr4Cuban + omelette2411rank 3does not raise itLoop over the columns: does the rank go up?r4 = r1 + r2: (2, 1, 1, 0) + (0, 3, 0, 1) = (2, 4, 1, 1)
picked = [1 2 3]: the same columns as the pivots of rref(R).

Three recipes, 1, 2 and 3, form a basis of the space spanned by the four, which has dimension 3. The trace table tells it pass by pass:

PassColumnRank of candidateColumns of B beforeDoes it stay?
1r1\mathbf{r}_110Yes
2r2\mathbf{r}_221Yes
3r3\mathbf{r}_332Yes
4r4\mathbf{r}_433No

The same table with the reason for each row:

  • Pass 1: B has no columns yet, so size(B, 2) is 0, and candidate is just r1 \mathbf{r}_1 , of rank 1. Since 1 > 0, it enters the if: B now has one column and picked is 1. The first column always stays, unless it is all zeros.
  • Pass 2: candidate is [r1 r2] and its rank is 2, greater than the one column already in B. It is what you saw by hand: the omelette is not a multiple of the Cuban rice.
  • Pass 3: rank 3 > 2. The rice with tomato and cheese cannot be made from the first two.
  • Pass 4: candidate has 4 columns, but its rank is still 3, and B already has 3 columns. Since 3 > 3 is false, it does not enter the if: neither B nor picked changes.

Why does the if compare with size(B, 2) and not with rank(B)? Because only columns that raised the rank get into B: they are always independent and their rank is exactly their number of columns. Counting them is immediate; rank would give the same number with more work.

Check you’ve got it: what does basis_of return if you give it the recipes in the order 4, 1, 2, 3?

It keeps 4, 1 and 3, and the redundant one is the omelette. Step by step: the first column it sees is r4 \mathbf{r}_4 , which is not zero: it stays. The second is r1 \mathbf{r}_1 , which is not a multiple of r4 \mathbf{r}_4 (the Cuban rice has no cheese and the Cuban rice with omelette does): it stays. The third is r2 \mathbf{r}_2 , and now r2=r4−r1 \mathbf{r}_2 = \mathbf{r}_4 – \mathbf{r}_1 : the rank does not go up and it does not get in. The fourth is r3 \mathbf{r}_3 , which raises the rank to 3. Since picked stores positions in the matrix it receives, it comes out as [1 2 4]: first, second and fourth column of R(:, [4 1 2 3]), which are r4 \mathbf{r}_4 , r1 \mathbf{r}_1 and r3 \mathbf{r}_3 .

R = [2 0 2 2; 1 3 0 4; 1 0 1 1; 0 1 1 1];
[B, picked] = basis_of(R(:, [4 1 2 3]))

function [B, picked] = basis_of(V)
    B = zeros(size(V, 1), 0);
    picked = [];
    for j = 1:size(V, 2)
        candidate = [B V(:, j)];
        if rank(candidate) > size(B, 2)
            B = candidate;
            picked(end+1) = j;
        end
    end
end

Output:

B =

     2     2     2
     4     1     0
     1     1     1
     1     0     1

picked =

     1     2     4

A different basis, with different recipes in it, but again of three vectors: the basis depends on the order in which you look, the dimension does not.

B = zeros(size(V, 1), 0) deserves an explanation: it is a matrix with 4 rows and 0 columns. It looks strange, but that way [B V(:, j)] works from the first pass (if B were plain [], it would also work, but size(B, 2) and the sizes are clearer like this).

Comparing with what MATLAB has: rref returns as its second output the pivot columns, which are exactly those of a basis, and null(R, 'r') gives the relation that explains why r4\mathbf{r}_4 is redundant:

[~, pivots] = rref(R)
relation = null(R, 'r')
norm(R * relation)

Output:

pivots =

     1     2     3

relation =

    -1
    -1
     0
     1

ans =

     0

The pivots match picked. And relation says −r1−r2+0 r3+r4=0-\mathbf{r}_1 – \mathbf{r}_2 + 0\,\mathbf{r}_3 + \mathbf{r}_4 = \mathbf{0}, that is, r4=r1+r2\mathbf{r}_4 = \mathbf{r}_1 + \mathbf{r}_2: Cuban rice with omelette is the Cuban rice plus the omelette. Checking by hand: (2,1,1,0)+(0,3,0,1)=(2,4,1,1)(2, 1, 1, 0) + (0, 3, 0, 1) = (2, 4, 1, 1). The 'r' in null asks for the “rational” basis, with simple numbers; without it, MATLAB gives it normalised and with decimals.

rank also works with a tolerance. That is why basis_of works with data with decimals: a vector that is “almost” a combination of the others (because of rounding) does not raise the rank.

Step 2: your own Gram-Schmidt

Gram-Schmidt (topic 4) turns a basis into an orthonormal basis: vectors of norm 1 that are perpendicular to each other. For each vector, you remove what it has in the direction of the ones already there and divide by its norm:

Before the formula, do it with the omelette. Gram-Schmidt starts with the Cuban rice: r1=(2,1,1,0) \mathbf{r}_1 = (2, 1, 1, 0) has norm 6≈2.449 \sqrt{6} \approx 2.449 , and dividing it by that norm gives q1 \mathbf{q}_1 : the same direction, with length 1.

Now the omelette arrives, r2=(0,3,0,1) \mathbf{r}_2 = (0, 3, 0, 1) . Is it perpendicular to the Cuban rice? Their dot product is 0+3+0+0=3 0 + 3 + 0 + 0 = 3 , so no: the omelette has “a bit of Cuban rice inside”, its shadow on the direction of r1 \mathbf{r}_1 . How much? The dot product divided by the square of the Cuban rice’s norm: 3/6=0.5 3/6 = 0.5 times r1 \mathbf{r}_1 , that is, (1; 0.5; 0.5; 0) (1;\ 0.5;\ 0.5;\ 0) .

If you remove it, you are left with w2=(0,3,0,1)−(1; 0.5; 0.5; 0)=(−1; 2.5; −0.5; 1) \mathbf{w}_2 = (0, 3, 0, 1) – (1;\ 0.5;\ 0.5;\ 0) = (-1;\ 2.5;\ -0.5;\ 1) . Check that it is now perpendicular to the Cuban rice: −2+2.5−0.5+0=0 -2 + 2.5 – 0.5 + 0 = 0 . All that is left is to divide it by its norm, 1+6.25+0.25+1=8.5≈2.915 \sqrt{1 + 6.25 + 0.25 + 1} = \sqrt{8.5} \approx 2.915 , and you have q2 \mathbf{q}_2 .

That is the whole algorithm: from each vector you remove its shadows on the ones you already have, and what is left is brought to length 1. The formula below says it for any pass; since each qk \mathbf{q}_k has norm 1, the shadow is written (qk⋅v) qk (\mathbf{q}_k \cdot \mathbf{v})\,\mathbf{q}_k , without dividing by anything.

wj=vj−∑k<j(qk⋅vj) qk,qj=wj∥wj∥ \mathbf{w}_j = \mathbf{v}_j – \sum_{k<j} (\mathbf{q}_k \cdot \mathbf{v}_j)\, \mathbf{q}_k, \qquad \mathbf{q}_j = \frac{\mathbf{w}_j}{\lVert \mathbf{w}_j \rVert}

First, the loop without a function, showing the norm of each wj\mathbf{w}_j before dividing. We give it the four recipes on purpose, the redundant one too:

Q = zeros(4, 0);
for j = 1:4
    w = R(:, j);
    for k = 1:size(Q, 2)
        w = w - (Q(:, k)' * w) * Q(:, k);   % remove the part in the direction of q_k
    end
    fprintf('Turn %d: norm of w = %.4g\n', j, norm(w));
    if norm(w) < 1e-10
        continue                           % it depends on the previous ones: out
    end
    Q(:, end+1) = w / norm(w);
end

Output:

Turn 1: norm of w = 2.449
Turn 2: norm of w = 2.915
Turn 3: norm of w = 1.252
Turn 4: norm of w = 8.631e-16
Gram-Schmidt turn by turnBars with the norm of w in each turn: about 2.449, 2.915 and 1.252 for the first three recipes, which become q1, q2 and q3, and about 1e-16 for the fourth, which the continue skips.What is left of each recipe after removing the earlier directionsturn 1: r1norm(w) = 2.449→ q1turn 2: r2norm(w) = 2.915→ q2turn 3: r3norm(w) = 1.252→ q3turn 4: r4norm(w) = 8.631·10⁻¹⁶continuetol = 1e-10: below it, it is a zero from rounding
The values are the ones printed by the loop; the fourth bar is not empty by mistake: it is 10¹⁶ times smaller.

In the first three passes, what is left of each recipe has a real norm. In the fourth, after removing what it has in the directions of q1\mathbf{q}_1, q2\mathbf{q}_2 and q3\mathbf{q}_3, nothing is left: a norm of the order of 10−1610^{-16}, which is the computer’s zero (your MATLAB may show another number of that size: those last digits depend on the order in which the computer does the sums). If we divided by it, the “unit vector” would be noise multiplied by 101610^{16}. The if with a tolerance and the continue prevent that, and on the way Gram-Schmidt becomes a dependence detector.

The four passes, with what the loop removes from each recipe and why:

PassRecipeWhat is removedWhat is left, w \mathbf{w} NormWhy
1r1 \mathbf{r}_1 nothing(2,1,1,0) (2, 1, 1, 0) 6≈2.449 \sqrt{6} \approx 2.449 Q is empty: the inner for does no passes and it only divides by the norm
2r2 \mathbf{r}_2 0.5 r1 0.5\,\mathbf{r}_1 (−1; 2.5; −0.5; 1) (-1;\ 2.5;\ -0.5;\ 1) 8.5≈2.915 \sqrt{8.5} \approx 2.915 its shadow on q1 \mathbf{q}_1 , the sum from before
3r3 \mathbf{r}_3 56 r1 \tfrac{5}{6}\,\mathbf{r}_1 and then −317 w2 -\tfrac{3}{17}\,\mathbf{w}_2 ≈(0.157; −0.392; 0.078; 1.176) \approx (0.157;\ -0.392;\ 0.078;\ 1.176) ≈1.252 \approx 1.252 r1⋅r3=4+0+1+0=5 \mathbf{r}_1 \cdot \mathbf{r}_3 = 4 + 0 + 1 + 0 = 5 , hence the 5/6 5/6 ; what is left still has a shadow on q2 \mathbf{q}_2 , a negative one, and removing it adds a little of w2 \mathbf{w}_2
4r4 \mathbf{r}_4 1.5 r1 1.5\,\mathbf{r}_1 , then the whole of w2 \mathbf{w}_2 and then nothing(0,0,0,0) (0, 0, 0, 0) 0 (on the computer, 10−16 10^{-16} )r1⋅r4=9 \mathbf{r}_1 \cdot \mathbf{r}_4 = 9 and 9/6=1.5 9/6 = 1.5 ; after removing the Cuban rice, (−1; 2.5; −0.5; 1) (-1;\ 2.5;\ -0.5;\ 1) is left, exactly what was left of the omelette, and removing it leaves nothing

Row 4 explains it all: since r4=r1+r2 \mathbf{r}_4 = \mathbf{r}_1 + \mathbf{r}_2 , it brings no new direction, and Gram-Schmidt detects it on its own.

Check you’ve got it: where do the numbers in the first two columns of Q come from?

They are r1 \mathbf{r}_1 and w2 \mathbf{w}_2 divided by their norms. Step by step: the first column is q1=(2,1,1,0)/2.449 \mathbf{q}_1 = (2, 1, 1, 0)/2.449 , and 2/2.449≈0.8165 2/2.449 \approx 0.8165 , 1/2.449≈0.4082 1/2.449 \approx 0.4082 and the 0 stays 0: it is exactly the first column MATLAB prints. The second is q2=(−1; 2.5; −0.5; 1)/2.915 \mathbf{q}_2 = (-1;\ 2.5;\ -0.5;\ 1)/2.915 , which gives −0.3430 -0.3430 , 0.8575 0.8575 , −0.1715 -0.1715 and 0.3430 0.3430 .

Two details of the code:

  • Q(:, k)' * w is the dot product qk⋅w\mathbf{q}_k \cdot \mathbf{w}: row times column gives a number. The same as dot(Q(:, k), w).
  • The projection is subtracted from w, the vector being updated, and not from the original R(:, j). With exact arithmetic it makes no difference; with decimals, this form (called modified Gram-Schmidt) loses much less orthogonality. It is the one you should always program.

The same idea, now as a reusable function:

function Q = gram_schmidt(V, tol)
% GRAM_SCHMIDT  Orthonormal basis (as columns) of the space spanned by the columns of V.
%   Q = gram_schmidt(V, tol) skips the vectors whose new part has norm < tol (1e-10 by default).
if nargin < 2
    tol = 1e-10;
end
Q = zeros(size(V, 1), 0);
for j = 1:size(V, 2)
    w = V(:, j);
    for k = 1:size(Q, 2)
        w = w - (Q(:, k)' * w) * Q(:, k);   % modified Gram-Schmidt
    end
    if norm(w) > tol
        Q(:, end+1) = w / norm(w);
    end
end
end

With the four recipes, the redundant one included:

Q = gram_schmidt(R)
orthonormal = norm(Q' * Q - eye(size(Q, 2)))

Output:

Q =

    0.8165   -0.3430    0.1252
    0.4082    0.8575   -0.3131
    0.4082   -0.1715    0.0626
         0    0.3430    0.9393

orthonormal =

   4.2930e-16

Q'*Q is the matrix of all the dot products between the columns of Q: if the basis is orthonormal, it is the identity (ones on the diagonal because each vector has norm 1, zeros elsewhere because they are perpendicular). The norm of the difference from eye(3) is of the order of 10−1610^{-16}: orthonormal, to the computer’s tolerance.

Comparing with MATLAB: the orth function also gives an orthonormal basis of the column space, but it computes it differently (with the SVD decomposition) and it comes out as another basis, with other numbers. You do not compare the numbers but the subspaces: if the columns of orth(R) are in the space spanned by Q, projecting them onto it does not change them.

O = orth(R);
size(O, 2)                         % also 3 vectors
norm(Q * (Q' * O) - O)             % projecting O onto the space of Q does not change it

Output:

ans =

     3

ans =

   4.2453e-16

Same dimension, and the difference is of the order of 10−1610^{-16}: both span the same subspace, each with its own basis.

Step 3: projection as a function

We want a week with d=(3,3,2,2)\mathbf{d} = (3, 3, 2, 2): 3 servings of rice, 3 of egg, 2 of tomato and 2 of cheese. Can we get it by combining the recipes? If d\mathbf{d} is not in the space they span, the best approximation is its orthogonal projection p\mathbf{p} onto that space (topic 4), and with an orthonormal basis it is a one-line formula: p=Q QTd\mathbf{p} = Q\,Q^{T}\mathbf{d}.

Before the code, a question for your head: why is there no exact combination? Look at the rice and tomato in the three recipes of the basis: 2 and 1, 0 and 0, 2 and 1. In all three, the rice is twice the tomato, and when you mix them, in whatever proportion, it still is. The week asks for 3 rice and 2 tomato, and 3 is not twice 2: no mix can do it. The egg and the cheese have no such tie.

So you can guess the answer: egg and cheese stay at 3 and 2, and rice and tomato settle on the “double” pair closest to 3 and 2. If the tomato is t t , the rice is 2t 2t , and how far it is from what you asked for is (2t−3)2+(t−2)2 (2t – 3)^2 + (t – 2)^2 . Differentiating and setting it to zero, 4(2t−3)+2(t−2)=0 4(2t – 3) + 2(t – 2) = 0 , that is, 10t=16 10t = 16 and t=1.6 t = 1.6 , with 3.2 3.2 rice. Write it down, (3.2; 3; 1.6; 2) (3.2;\ 3;\ 1.6;\ 2) , and check that the function gets the same.

function [p, c] = project(v, B)
% PROJECT  Orthogonal projection of v onto the space spanned by the columns of B.
%   [p, c] = project(v, B) returns the projection p and the coefficients c with p = B*c.
Q = gram_schmidt(B);
if size(Q, 2) < size(B, 2)
    error('project:dependent', ...
          'The columns of B are not independent: rank %d of %d.', size(Q, 2), size(B, 2));
end
p = Q * (Q' * v);
c = B \ p;                       % how much of each column of B
end

Three design decisions:

  • It uses gram_schmidt instead of repeating its loop: a function can (and should) call others.
  • If the columns of B are dependent, the coefficients would not be unique, so the function stops with an error that explains why. The ... at the end of the line continues the instruction on the next one.
  • c = B \ p solves Bc=pB\mathbf{c} = \mathbf{p}, which has an exact solution because p\mathbf{p} is in the space of BB.
d = [3; 3; 2; 2];
[p, c] = project(d, B)
diet_error = norm(d - p)
perpendicular = norm(B' * (d - p))

Output:

p =

    3.2000
    3.0000
    1.6000
    2.0000

c =

    0.4500
    0.8500
    1.1500

diet_error =

    0.4472

perpendicular =

   2.5704e-15
The projection of the target weekThe target week d sticks out of the plane of the recipes; its projection p lies on the plane and the error d minus p is perpendicular to it, with norm 0.4472.span(r1, r2, r3)d = (3, 3, 2, 2)p = (3.2, 3, 1.6, 2)d − p = (−0.2, 0, 0.4, 0)norm = 0.4472B'·(d − p) ≈ 0perpendicular to every recipep = 0.45·r1 + 0.85·r2 + 1.15·r3
A drawing of the idea: the space is 3-dimensional inside R⁴, but the right angle is the same.

The closest week we can cook has 3.2 of rice, 3 of egg, 1.6 of tomato and 2 of cheese, and it comes from 0.45 servings of Cuban rice, 0.85 of omelette and 1.15 of rice with tomato. Checking the rice by hand: 2⋅0.45+0⋅0.85+2⋅1.15=0.9+2.3=3.22 \cdot 0.45 + 0 \cdot 0.85 + 2 \cdot 1.15 = 0.9 + 2.3 = 3.2. The error is d−p=(−0.2; 0; 0.4; 0)\mathbf{d} – \mathbf{p} = (-0.2;\ 0;\ 0.4;\ 0), with norm 0.04+0.16=0.4472\sqrt{0.04 + 0.16} = 0.4472. And the last line checks the property that defines the projection: the error is perpendicular to every recipe (BT(d−p)≈0B^{T}(\mathbf{d} – \mathbf{p}) \approx \mathbf{0}).

The error (−0.2; 0; 0.4; 0) (-0.2;\ 0;\ 0.4;\ 0) is −0.2 -0.2 times (1,0,−2,0) (1, 0, -2, 0) , the direction of “rice minus twice the tomato”: the only one the recipes cannot touch.

Check you’ve got it: what comes out if the week you want is 4 rice, 3 egg, 2 tomato and 2 cheese?

It comes out exact: the projection is the week itself and the error is 0. Step by step: 4 rice is twice 2 tomato, so the week meets the recipes’ only tie and is in the space they span. Projecting a vector that is already in the space leaves it unchanged. The coefficients come from c1+c3=2 c_1 + c_3 = 2 (tomato), c2+c3=2 c_2 + c_3 = 2 (cheese) and c1+3c2=3 c_1 + 3c_2 = 3 (egg): c1=c2=0.75 c_1 = c_2 = 0.75 and c3=1.25 c_3 = 1.25 . Checking the rice: 2⋅0.75+2⋅1.25=4 2 \cdot 0.75 + 2 \cdot 1.25 = 4 . With MATLAB:

R = [2 0 2 2; 1 3 0 4; 1 0 1 1; 0 1 1 1];
B = R(:, 1:3);
d2 = [4; 3; 2; 2];
c = B \ d2
diet_error = norm(d2 - B*c)

Output:

c =

    0.7500
    0.7500
    1.2500

diet_error =

   1.6012e-15

The same coefficients, and an error that is the computer’s zero.

Comparing with MATLAB: B \ d, with BB having more rows than columns, does not give an error: it gives the least squares solution, which is exactly that projection:

c2 = B \ d
difference = norm(B*c2 - p)

Output:

c2 =

    0.4500
    0.8500
    1.1500

difference =

   2.2753e-15

The same coefficients. Your function and the backslash get to the same place by different roads.

And if we pass it the four recipes, with the redundant one?

project(d, R)

Output:

The columns of B are not independent: rank 3 of 4.

The function’s error fires with its message. A clear error is better than coefficients that mean nothing.

Common mistakes (with MATLAB’s real message)

1. Going past the end of the vector. A loop that does one pass too many:

v = [2 1 1 0];
for k = 1:5
    total = v(k);
end

Output:

Index exceeds the number of array elements. Index must not exceed 4.

It is the 1:5 when the vector has 4. Always use 1:numel(v) or 1:size(A, 2), never the number typed by hand.

2. Matrices of different sizes. Comparing Q'*Q with an identity of the wrong size:

norm(Q' * Q - eye(4))

Output:

Arrays have incompatible sizes for this operation.

Q'*Q is 3×33 \times 3 because there are only three vectors in the basis. Hence the eye(size(Q, 2)) from before.

3. The sum that gives no error and should. A row plus a column:

[2 1 1 0] + [2; 1; 1; 0]

Output:

ans =

     4     3     3     2
     3     2     2     1
     3     2     2     1
     2     1     1     0

No error: MATLAB “expands” the row and the column and returns a 4×44 \times 4 matrix with every possible sum. If you meant to add two recipes and one came as a row, the result is wrong and nobody warns you. With recipe vectors, everything as columns.

4. Comparing with == something that comes from a square root. The dot product of two vectors of Q should be 0:

Q(:, 1)' * Q(:, 2) == 0
abs(Q(:, 1)' * Q(:, 2)) < 1e-10

Output:

ans =

  logical

   0

ans =

  logical

   1
  • The loop variable reused. If inside a for k you call something that also uses k in the same script, they overwrite each other. Inside a function it does not happen: each one has its own variables.
  • A while with no way out. Ctrl+C and check what changes inside.
  • i and j as counters before using complex numbers: write 1i.

Try it in the MATLAB playground

In the site’s MATLAB playground you can run this script, with Gram-Schmidt as a local function at the end:

% Flat recipes: orthonormal basis and the closest week
R = [2 0 2 2; 1 3 0 4; 1 0 1 1; 0 1 1 1];
Q = gs(R);
fprintf('Dimension of the recipe space: %d\n', size(Q, 2));
d = [3; 3; 2; 2];
p = Q * (Q' * d)
fprintf('Error: %.4f\n', norm(d - p));

function Q = gs(V)
Q = zeros(size(V, 1), 0);
for j = 1:size(V, 2)
    w = V(:, j);
    for k = 1:size(Q, 2)
        w = w - (Q(:, k)' * w) * Q(:, k);
    end
    if norm(w) > 1e-10
        Q(:, end+1) = w / norm(w);
    end
end
end

Things to look at:

  1. Change the fourth recipe to [1; 1; 1; 1] (another column of R): now the four are independent, the dimension goes up to 4 and the error of the week becomes 0.
  2. Remove the if norm(w) > 1e-10 and leave only the line inside it: with the original recipes, the fourth column of Q comes out with huge or strange numbers.
  3. In the Workspace, look at Q and compute Q'*Q in the Command Window.
  4. Write d = [3 3 2 2] (as a row) and look at what happens with Q' * d.

Summary

PieceWhat forExample
forKnown number of passesfor j = 1:size(R, 2)
for over a matrixGo through columnsfor r = R
whileRepeat while something holdswhile all(left >= r1)
break / continueLeave / jump to the next passif norm(w) < tol, continue, end
Growing vectorStore results without knowing how manypicked(end+1) = j
Logical vectorPick elements or columnsR(:, chosen)
ToleranceCompare decimalsnorm(u - v) < 1e-10
error in a functionStop with a clear messageerror('id:reason', 'text %d', n)

Three ideas to take away:

  1. for if you know how many passes, while if how many is what you want to know. And in the while, something inside has to bring the condition closer to false.
  2. A linear algebra algorithm is a loop over columns. Basis, Gram-Schmidt and projection share the same structure: go through, decide with an if and store.
  3. With decimals, zero means “smaller than a tolerance”. Gram-Schmidt without a tolerance divides by noise; with it, it also detects the redundant vectors.

Now it is your turn: in the block 2 exercises of the intensive course you will program the change of basis, coordinates in a basis and Gram-Schmidt with another inner product, with commented solutions, “What is wrong here?” and a cheat sheet.

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

Next step: exercisesVector 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)Cheat sheet: the block on one page, to reviewCheat sheetLab assignments: the block's functions and a model scriptFor your lab assignments