function E = modgrsch(V)
%modgrschmidt  Modified Gram-Schmidt for converting a set of linearly
%independent vectors to an set of orthonormal vectors spanning the
%same subspace.
%
%   E = modgrsch(V), where V is an m x k matrix, and E is an m x k matrix
%   whose columns are an orthonormal set of vectors that span the same
%   subspace as the columns of V.

[m, k] = size(V);
% allocate the output matrix E
E = zeros(m, k);

% begin the computation
for i=1:k
	E(:,i) = V(:,i);
	for j=1:i-1
		E(:,i) = E(:,i) - E(:,j)'*E(:,i)*E(:,j);
	end
	% normalize E(:,i)
	E(:,i) = E(:,i)/norm(E(:,i));	
end