%MATLAB implementation of the modified Gram-Schmidt.
function [Q,R] = mgs(A);

[m,n] = size(A);
%if m ~= n
%	disp('m must be equal to n in this function!');
%end

R = zeros(n);

%initialize v:
V = A;

for i=1:n
	R(i,i) = norm(V(:,i));
	Q(:,i) = V(:,i)/R(i,i);
	for j=i+1:n
		R(i,j) = Q(:,i)'*V(:,j);
		V(:,j) = V(:,j) - R(i,j)*Q(:,i);
	end
end
