function [N,M,k,l] = null2(A,method,tol)
% PURPOSE: returns an orthonormal basis of the null space and range of A
%
% ---------------------------------------------------
% USAGE: [N,M,k,l] = null2(A,method,tol)
% where:
% A a matrix
% method method used
% 1 - qr with pivoting
% 2 - svd
% tol uses the tolerance tol when calculating
% null subspaces (optional)
%
% N an orthonormal basis of the null space
% of A
% M an orthonormal basis of the range of A
% k null space dimension
% l range dimension
%
% COMMENTS:
% Calculating null space using qr decomposition is facter than using
% svd decomposition but less accurate.
% If one requires very precise null space
% or null space and range are not clearly separated, then version based
% on svd decomposition should be used.
%
% Copyright (c) Pawel Kowal (2006)
% All rights reserved
% LREM_SOLVE toolbox is available free for noncommercial academic use only.
% pkowal3@sgh.waw.pl
if nargin<3
tol = 10 * max(size(A)) * norm(A,1) * eps;
end
switch method
case 1
[Q,R,P] = qr(A');
k = rank2(R,tol);
N = Q(:,k+1:end);
M = Q(:,1:k);
k = size(Q,2)-k;
case 2
[U,S,V] = svd(A);
if size(A,1)>1 && size(A,2)>1
s = diag(S);
else
s = S;
end
tol = 10*max(size(A)') * eps(max(s));
k = sum(s>tol);
N = V(:,k+1:end);
M = V(:,1:k);
end
l = size(A,1)-k;