%% Rank, Column Space, and Null Space of Matrix
% Use the results of the singular value decomposition to determine the rank, column space, and null space of a matrix.

A = [2 0 2; 0 1 0; 0 0 0]

%

[U,S,V] = svd(A)

%
% Calculate the rank using the number of nonzero singular values.

s = diag(S);
rank_A = nnz(s)

%
% Compute an orthonormal basis for the column space of A using the columns of U that correspond to nonzero singular values.

column_basis = U(:,logical(s))

%
% Compute an orthonormal basis for the null space of A using the columns of V that correspond to singular values equal to zero.

null_basis = V(:,~s)

% The functions rank, orth, and null provide convenient ways to calculate these quantities.
% Copyright 2012 The MathWorks, Inc.