I'm trying to write a program that gets a matrix A
of any size, and SVD decomposes it:
A = U * S * V'
Where A
is the matrix the user enters, U
is an orthogonal matrix composes of the eigenvectors of A * A'
, S
is a diagonal matrix of the singular values, and V
is an orthogonal matrix of the eigenvectors of A' * A
.
Problem is: the MATLAB function eig
sometimes returns the wrong eigenvectors.
This is my code:
function [U,S,V]=badsvd(A)
W=A*A';
[U,S]=eig(W);
max=0;
for i=1:size(W,1) %%sort
for j=i:size(W,1)
if(S(j,j)>max)
max=S(j,j);
temp_index=j;
end
end
max=0;
temp=S(temp_index,temp_index);
S(temp_index,temp_index)=S(i,i);
S(i,i)=temp;
temp=U(:,temp_index);
U(:,temp_index)=U(:,i);
U(:,i)=temp;
end
W=A'*A;
[V,s]=eig(W);
max=0;
for i=1:size(W,1) %%sort
for j=i:size(W,1)
if(s(j,j)>max)
max=s(j,j);
temp_index=j;
end
end
max=0;
temp=s(temp_index,temp_index);
s(temp_index,temp_index)=s(i,i);
s(i,i)=temp;
temp=V(:,temp_index);
V(:,temp_index)=V(:,i);
V(:,i)=temp;
end
s=sqrt(s);
end
My code returns the correct s
matrix, and also "nearly" correct U
and V
matrices. But some of the columns are multiplied by -1. obviously if t
is an eigenvector, then also -t
is an eigenvector, but with the signs inverted (for some of the columns, not all) I don't get A = U * S * V'
.
Is there any way to fix this?
Example: for the matrix A=[1,2;3,4]
my function returns:
U=[0.4046,-0.9145;0.9145,0.4046]
and the built-in MATLAB svd
function returns:
u=[-0.4046,-0.9145;-0.9145,0.4046]