% Calculate nullspace using SVD
clear all

% Define A matrix
disp('The A matrix')
A=[1 2 0;0 -1 1;0 0 0;0 0 0]

[m,n]=size(A);    %m-number of rows, n-number of columns
[U,S,V]=svd(A);   % The singular value decomposition

disp(diag(S)')    % The singular values, number of non-zero singular values equal the rank, r
r=2;              % The rank of A

% SVD such that_ A=U*S*V' =U1*S1*V1' + U2*S2*V2'
U1=U(:,1:r); S1=S(1:r,1:r); V1=V(:,1:r)
U2=U(:,r+1:n); S2=S(r+1:n,r+1:n); V2=V(:,r+1:n);

U1*S1*V1'+U2*S2*V2'  % Check if A=U1*S1*V1' + U2*S2*V2'

x=V2;      % The nullspace vector such that A*x =0
A*x            