MATLAB: SVD issue calculating null basis

matrixstatisticssvd

I am tyring to reproduce the image results for V. I have written the following code. However, the V produced by svd command is not matching what I should see. I have double checked my G matrix and the S output is correct. Any advice appreciated.
%create the matrix, run svd
G=[1 0 0 1 0 0 1 0 0; 0 1 0 0 1 0 0 1 0; 0 0 1 0 0 1 0 0 1; 1 1 1 0 0 0 0 0 0;
0 0 0 1 1 1 0 0 0; 0 0 0 0 0 0 1 1 1; sqrt(2) 0 0 0 sqrt(2) 0 0 0 sqrt(2); 0 0 0 0 0 0 0 0 sqrt(2)];
[U,S,V] = svd(G,0);
s_d=diag(S);
%The model null space, N(G), is spanned by the two orthonormal vectors
%that form the 8th and 9th columns of V. An orthonormal basis for the null space is
s = diag(S);
column_basis = U(:,logical(s));
rank_G= nnz(s);
null_basis=V(:,~s);

Best Answer

The problem is that while the last element of s is small, it is not technically zero.
s
s =
3.17982071419273
2
1.73205080756888
1.73205080756888
1.73205080756888
1.60697051494866
0.553521444640095
8.80988299920657e-17
>> nnz(s)
ans =
8
So what does nnz tell you? Hey it is not zero after all. 8.8e-17 is tiny, but is it zero?
s == 0
ans =
8×1 logical array
0
0
0
0
0
0
0
0
In fact, that least element is close enough to zero for our purposes that here, we consider it to be so. But it is not in fact zero, and nnz is rather strict. As far as nnz cares, it simply is not zero.
You might do something like this:
sum(s >= eps*max(s))
ans =
7
Here we see that what matters is if the smallest number really is tiny, when compared to the maximum element in the vector s. Note that I am not worried about whether elements of s are negative, because they are singular values! Otherwise, I might have needed a call to abs in there.