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.
Table of Contents
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.
| Recipe | Rice | Egg | Tomato | Cheese |
|---|---|---|---|---|
| Cuban-style rice | 2 | 1 | 1 | 0 |
| Cheese omelette | 0 | 3 | 0 | 1 |
| Rice with tomato and cheese | 2 | 0 | 1 | 1 |
| Cuban rice with omelette | 2 | 4 | 1 | 1 |
Put as columns they form a matrix . 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 ? (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 .
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.
| Pass | j | R(:, j) | sum(R(:, j)) | Why |
|---|---|---|---|---|
| 1 | 1 | 4 | 1:4 starts at 1: the first column, the Cuban rice | |
| 2 | 2 | 4 | the body is the same; only j changes | |
| 3 | 3 | 4 | same again: another column, the same sum | |
| 4 | 4 | 8 | last 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
forcan be anything:for j = [4 1 3]goes in that order andfor j = 10:-2:4counts down (10, 8, 6, 4). - If you give the
fora matrix, it goes through its columns:for r = Rmakes four passes, and in each oneris 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:
| Pass | left before | all(left >= r1)? | left after | servings | Why |
|---|---|---|---|---|---|
| 1 | yes | 1 | there is plenty of everything; it subtracts 2, 1, 1 and 0 | ||
| 2 | yes | 2 | the cheese does not go down: the Cuban rice has none | ||
| 3 | yes | 3 | there is still enough of each ingredient | ||
| 4 | yes | 4 | still enough for another dish | ||
| 5 | yes | 5 | the last possible dish: rice and tomato go down to 0 | ||
| (6) | no | not run | 5 | 0 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 . You start with ; there is enough, and is left. There is enough again (exactly 3 eggs), and 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 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?
- : I do not have any yet, and it is not the zero vector. I keep it.
- : 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.
- : is it ? The rice says , so . The egg says , so . But the cheese says . It cannot be both at once: it cannot be made from the previous ones. I keep it.
- : try the Cuban rice plus the omelette: . 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: 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
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:
| Pass | Column | Rank of candidate | Columns of B before | Does it stay? |
|---|---|---|---|---|
| 1 | 1 | 0 | Yes | |
| 2 | 2 | 1 | Yes | |
| 3 | 3 | 2 | Yes | |
| 4 | 3 | 3 | No |
The same table with the reason for each row:
- Pass 1:
Bhas no columns yet, sosize(B, 2)is 0, andcandidateis just , of rank 1. Since 1 > 0, it enters theif:Bnow has one column andpickedis1. The first column always stays, unless it is all zeros. - Pass 2:
candidateis[r1 r2]and its rank is 2, greater than the one column already inB. 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:
candidatehas 4 columns, but its rank is still 3, andBalready has 3 columns. Since 3 > 3 is false, it does not enter theif: neitherBnorpickedchanges.
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 , which is not zero: it stays. The second is , which is not a multiple of (the Cuban rice has no cheese and the Cuban rice with omelette does): it stays. The third is , and now : the rank does not go up and it does not get in. The fourth is , 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 , and .
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 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 , that is, : Cuban rice with omelette is the Cuban rice plus the omelette. Checking by hand: . 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: has norm , and dividing it by that norm gives : the same direction, with length 1.
Now the omelette arrives, . Is it perpendicular to the Cuban rice? Their dot product is , so no: the omelette has “a bit of Cuban rice inside”, its shadow on the direction of . How much? The dot product divided by the square of the Cuban rice’s norm: times , that is, .
If you remove it, you are left with . Check that it is now perpendicular to the Cuban rice: . All that is left is to divide it by its norm, , and you have .
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 has norm 1, the shadow is written , without dividing by anything.
First, the loop without a function, showing the norm of each 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
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 , and , nothing is left: a norm of the order of , 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 . 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:
| Pass | Recipe | What is removed | What is left, | Norm | Why |
|---|---|---|---|---|---|
| 1 | nothing | Q is empty: the inner for does no passes and it only divides by the norm | |||
| 2 | its shadow on , the sum from before | ||||
| 3 | and then | , hence the ; what is left still has a shadow on , a negative one, and removing it adds a little of | |||
| 4 | , then the whole of and then nothing | 0 (on the computer, ) | and ; after removing the Cuban rice, is left, exactly what was left of the omelette, and removing it leaves nothing |
Row 4 explains it all: since , 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 and divided by their norms. Step by step: the first column is , and , and the 0 stays 0: it is exactly the first column MATLAB prints. The second is , which gives , , and .
Two details of the code:
Q(:, k)' * wis the dot product : row times column gives a number. The same asdot(Q(:, k), w).- The projection is subtracted from
w, the vector being updated, and not from the originalR(:, 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 : 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 : both span the same subspace, each with its own basis.
Step 3: projection as a function
We want a week with : 3 servings of rice, 3 of egg, 2 of tomato and 2 of cheese. Can we get it by combining the recipes? If is not in the space they span, the best approximation is its orthogonal projection onto that space (topic 4), and with an orthonormal basis it is a one-line formula: .
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 , the rice is , and how far it is from what you asked for is . Differentiating and setting it to zero, , that is, and , with rice. Write it down, , 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_schmidtinstead of repeating its loop: a function can (and should) call others. - If the columns of
Bare 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 \ psolves , which has an exact solution because is in the space of .
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 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: . The error is , with norm . And the last line checks the property that defines the projection: the error is perpendicular to every recipe ().
The error is times , 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 (tomato), (cheese) and (egg): and . Checking the rice: . 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 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 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 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 kyou call something that also useskin the same script, they overwrite each other. Inside a function it does not happen: each one has its own variables. - A
whilewith no way out. Ctrl+C and check what changes inside. iandjas counters before using complex numbers: write1i.
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:
- Change the fourth recipe to
[1; 1; 1; 1](another column ofR): now the four are independent, the dimension goes up to 4 and the error of the week becomes 0. - Remove the
if norm(w) > 1e-10and leave only the line inside it: with the original recipes, the fourth column ofQcomes out with huge or strange numbers. - In the Workspace, look at
Qand computeQ'*Qin the Command Window. - Write
d = [3 3 2 2](as a row) and look at what happens withQ' * d.
Summary
| Piece | What for | Example |
|---|---|---|
for | Known number of passes | for j = 1:size(R, 2) |
for over a matrix | Go through columns | for r = R |
while | Repeat while something holds | while all(left >= r1) |
break / continue | Leave / jump to the next pass | if norm(w) < tol, continue, end |
| Growing vector | Store results without knowing how many | picked(end+1) = j |
| Logical vector | Pick elements or columns | R(:, chosen) |
| Tolerance | Compare decimals | norm(u - v) < 1e-10 |
error in a function | Stop with a clear message | error('id:reason', 'text %d', n) |
Three ideas to take away:
forif you know how many passes,whileif how many is what you want to know. And in thewhile, something inside has to bring the condition closer to false.- A linear algebra algorithm is a loop over columns. Basis, Gram-Schmidt and projection share the same structure: go through, decide with an
ifand store. - 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


