% Exercise 4 of Midterm for Math 496 (text Exercise 4.4, page 87)
clear
% get the data
load 'ifk.mat'
m = length(d);
n = m; % for full matrix
s = linspace(0.025,0.975, m)';
dx = 1/n;
x = linspace(dx/2,1-dx/2,n)';
[X,S] = meshgrid(x,s);
G = X.*exp(-X.*S)*dx;
disp('The ratios of singular values of the coefficient matrix are:')
[U,S,V] = svd(G);
disp(diag(S)'/S(1,1));
% based on above data, choose truncation point
figure, hold all, grid
p = 2;
msoln = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(x,msoln);
p = 3;
msoln = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(x,msoln);
p = 4;
msoln = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(x,msoln);
title('TSVD collocation approximations to curve using p=2,3,4');
legend('p=2','p=3','p=4');
figure, hold all, grid
p = 5;
msoln = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(x,msoln);
title('TSVD collocation approximations to curve using p=5');
legend('p=5');
% As an illustrative alternate, we apply these ideas
% to Exercise 3.2, which we worked out.
% generate the full Gramian matrix
G = zeros(m,n);
for ii = 1:m
  for jj = ii:n
    a = s(ii)+s(jj);
    G(ii,jj) = 3*exp(-a)*(exp(a)-1-a-a^2/2)/a^3;
    G(jj,ii) = G(ii,jj);
  end
end
% for plotting solutions
xnodes = (0:.01:1)';
[X,S] = meshgrid(xnodes,s);
Gvalues = (X.*exp(-S.*X))';
disp('The ratios of singular values of the Gramian are:')
[U,S,V] = svd(G);
disp(diag(S)'/S(1,1));
% based on above data, choose truncation point
figure, hold all, grid
p = 2;
m = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(xnodes,Gvalues*m);
p = 3;
m = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(xnodes,Gvalues*m);
p = 4;
m = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(xnodes,Gvalues*m);
title('TSVD representer approximations to curve using p=2,3,4');
legend('p=2','p=3','p=4');
figure, hold all, grid
p = 5;
m = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(xnodes,Gvalues*m);
p = 6;
m = V(:,1:p)*inv(S(1:p,1:p))*U(:,1:p)'*d;
plot(xnodes,Gvalues*m);
title('TSVD representer approximations to curve using p=5,6');
legend('p=5','p=6');
