I have matrix A and matrices [U,S,V], such that [U, S, V] = svd(A).
How could I amend my script in matlab to get the 10 columns of U that correspond to the 10 largest singular values of A (i.e. the largest values in S)?
Thanks
If you recall the definition of the svd
, it is essentially solving an eigenvalue problem such that:
Av = su
v
is a right-eigenvector from the matrix V
and u
is a left-eigenvector from the matrix U
. s
is a singular value from the matrix S
. You know that S
is a diagonal matrix where these are the singular values sorted in descending order. As such, if we took the first column of v
and the first column of u
, as well as the first singular value of s
(top-left corner), if we did the above computation, we should get both outputs to be the same.
As an example:
rng(123);
A = randn(4,4);
[U,S,V] = svd(A);
format long;
o1 = A*V(:,1);
o2 = S(1,1)*U(:,1);
disp(o1);
disp(o2);
-0.267557887773137
1.758696945035771
0.934255531699997
-0.978346339659143
-0.267557887773136
1.758696945035771
0.934255531699996
-0.978346339659143
Similarly, if we looked at the second columns of U
and V
with the second singular value:
o1 = A*V(:,2);
o2 = S(2,2)*U(:,2);
disp(o1);
disp(o2);
0.353422275717823
-0.424888938462465
1.543570300948254
0.613563185406719
0.353422275717823
-0.424888938462465
1.543570300948252
0.613563185406719
As such, the basis vectors are arranged such that the columns are arranged from left to right in the same order as what the singular values dictate. As such, you simply grab the first 10 columns of U
. This can be done by:
out = U(:,1:10);
out
would contain the basis vectors, or columns of U
that correspond to the 10 highest singular values of A
.
First you sort the singular values, and save the reindexing, then take the first 10 values:
[a, b]=sort(diag(S));
Umax10=U(:,b(1:10));
As mentioned by Rayryeng, svd
outputs the singular values in decreasing order so:
Umax10=U(:,1:10);
is enough.
Just have to remember that it is not the case for eig
, even though it may seems that eig
also outputs ordered eigenvalues it is not always the case.
S
are already ordered largest to smallest. You would just take the first 10 columns ofU
. – eigenchris