function theta = subspace(a,b)
%SUBSPACE Angle between two subspaces.
%	SUBSPACE(A,B) finds the angle between two subspaces specified
%	by the columns of A and B.  If A and B are vectors of unit
%	length, this is the same as ACOS(A'*B).
%	If the angle is small, the two spaces are nearly linearly
%	dependent.  In a physical experiment described by some
%	observations A, and a second realization of the experiment
%	described by B, SUBSPACE(A,B) gives a measure of the amount
%	of new information afforded by the second experiment not
%	associated with statistical errors of fluctuations.

%	L. Shure 11-03-88.
%	Copyright (c) 1984-93 by The MathWorks, Inc.

a = a.'; b = b.';
[ma,na]=size(a);
[mb,nb]=size(b);
if ma ~= mb
   error('Column dimensions of A and B must be the same.')
end
[qa,ra]=qr(a);
[qb,rb]=qr(b);
qa = qa(:,1:na);
qb = qb(:,1:nb);
g=qa'*qb;
% the max singular value is the correct one to choose but should have magnitude
% no more than 1.
theta = acos(min(max(max(svd(g)),-1),1));
