
#linearni algebra
function cviceni4

rand("seed",1)

# sing. matice a , nesing. matice b

a=rand(5)-rand(5);
b=a;
a(:,4)=a(:,1)+a(:,2);
a(:,5)=a(:,1)-a(:,2)-a(:,3)-a(:,4);


[ve,lam]=eig(a)
[u,s,v]=svd(a)
norm(u*s*v'-a)
nu=null(a)
a*v(:,4)
or=orth(a)
nu(:,1)'*or(:,1) # neni ortogonalni

#inverze a nejmensi ctverce
#invertibilni
[u,s,v]=svd(b)
inverze=v*s^-1*u'
norm(inverze-inverse(b))

#singularni
[u,s,v]=svd(a)
s2=zeros(5); s2(1:3,1:3)=s(1:3,1:3)^-1;
bin=u(:,1)+u(:,2)-2*u(:,3); # vektor v range
bout=u(:,1)+u(:,4); # vektor mimo range

#pseudoinverze
pseudoinv=v*s2*u'
pinv(a)
norm(pinv(a)-pseudoinv)

#reseni singularni soustavy
# prava strana v range
x=pseudoinv*bin
x2=x+v(:,4);
a*x-bin
a*x2-bin
# x ma mensi normu nez x2
norm(x)
norm(x2)

# reseni singularni soustavy
# prava strana mimo range
xprox=pseudoinv*bout
# projekce bout na range
xprox2=pseudoinv*u(:,1)
a*xprox-bout
a*xprox2-bout


# konstrukce ortonorm. baze

v1=rand(5,1)
v2=rand(5,1)
v3=rand(5,1)

a=[v1,v2,v3];
a
[u,s,v]=svd(a)
proj=u(:,1)*u(:,1)'+u(:,2)*u(:,2)'+u(:,3)*u(:,3)'
eig(proj)
norm(proj*v3-v3)

# herm. sing. mat.
v1=rand(5,1)-I*rand(5,1)
v2=rand(5,1)+I*rand(5,1)
v3=rand(5,1)+I*rand(5,1)-rand(5,1)
b=v1*v1'-0.5*v2*v2'+0.3*v3*v3'
[ve,lam]=eig(b)
[u,s,v]=svd(b)
u(:,1)./ve(:,1)
b*ve(:,1)-lam(1,1)*ve(:,1)
# sing. cisla Herm. matice jsou abs hodnoty vl. cisel
s-abs(lam)



# vice rovnic min ctverce
a=rand(10,5);
x=rand(5,1)
b=a*x;
pseudoinv=pinv(a);
reseni=pseudoinv*b
chyba=rand(10,1)/100;
b2=b+chyba;
pseudoinv*b2


endfunction
