HMC Math 73: Linear Algebra (Spring, 1999)
Further hints for HW Problem HW#9A
(Writing a Gram-Schmidt function)

To start with, here's a copy of my function, with certain lines of code replaced by comments. You should be able to get yours to work simply by replacing these comment lines with code.

function B = gs(A)

for u=A
  for v=B
    % B's columns are the orthogonal vectors computed so far.
    % Subtract the appropriate multiple of of v from x
  if norm(x)>.0000001
    % Append x to B
for j=1:size(B,2)
  % divide B's j-th column by it's length
What's going on with "for u=A"? Okay... I assume you've seen "for n=1:5" for the standard "for" loop. What is "1:5"? Go to the MATLAB command line and type "1:5". What do you get? [1 2 3 4 5]. "1:5" is actually a vector. The each trip thru the loop sets n to the next entry in this vector. Now try typing this at the command line (the loop won't execute until you type "end")...
for n=[1 2 4 7 -2 0.5]
The "n" in the middle just prints the current value of n, which is each of the given values, in turn. More generally, "for u=A" sets u equal to a new column of A on each trip thru the loop. So "for u=A" can be used to process one column of A at a time, without worring about an artificial indexing variable like "i". The next for loop "for v=B" is doing the same thing... we want to subtract a multiple of each column of B from x, and this for loop handles moving thru these columns.

"if norm(x)>.0000001" is our crude check that x is not zero (for our simple integer examples, "norm(x)" should always be larger than this if x isn't 0... a real MATLAB function would be a lot more careful about this point). The other note tells exactly how to append x as the last column of B.

In the final "for" loop, we change the columns of B from orthogonal to orthonormal. Note that here, I am using a dummy variable to index to columns of B. Why? Because I want to read and write into the column, so setting a variable equal to it is not sufficient. There still might be a way to do this using "for v=B", but I couldn't think of any quickly. Once again, syntax for accessing the j-th column of B may be found here.

As a final random note, a semicolon at the end of a line supresses output (as in "x=u;"). This is not neccessary for control statements (for, if, end, etc.).