function [x,y,A] = TSPCAExample(n)

    % GENERATE AND PLOT THE DATASET
    [x,y] = TSGenerateData(n,2);
    figure;
    hold on;
    plot(x,y,'.');
    
    % COMPUTE THE SVD
    A(1,:) = x; % x is the first row
    A(2,:) = y; % y is the second row
    [U,S,V] = svd(A);

    % PLOT s1 u1
    TSPlotVec(U(:,1)*S(1,1),'r');
    
    % PLOT s2 u2
    TSPlotVec(U(:,2)*S(2,2),'b');
  
    % PLOT THE DATASET BY COMPONENTS
    % PLOT s1 u1 v1' and s2 u2 v2'
    TSPlotComponents(U,S,V);
    
    % COMPARE TO THE LS solution
    TSLeastSquares(A);

    % HOW ARE SVD AND LS AFFECTED BY AN OUTLIER?
%    x(1) = -2;
%    y(1) = 3;
%    A(1,:) = x;
%    A(2,:) = y;
%    [U,S,V] = svd(A);
%    TSPlotVec(U(:,1)*S(1,1),'b');
%    TSLeastSquares(A);
    
    % SQUARE ASPECT RATIO
    axis([-3,3,-3,3],"square")

end

function TSLeastSquares(A)
    a = A(1,:);
    b = A(2,:);
    mls = (a*b')/(a*a');
    TSPlotLine([1,mls],min(A(1,:)),max(A(2,:)));
end

function [x,y]=TSGenerateData(n,p)
    m = 2.1;
    x = rand(1,n)*2-1;
    y = m*x + rand(1,n)*p;
    
    % center the data
    x = x-mean(x);
    y = y-mean(y);
end

function TSPlotLine(dir,minx,maxx)
    x = [minx maxx];
    y = x * dir(2)/dir(1);
    plot(x,y,"k","linewidth",2);
end

function TSPlotVec(dir,color)
    x = [-dir(1)/2 dir(1)/2];
    y = [-dir(2)/2 dir(2)/2];
    plot(x,y,color,"linewidth",3);
end

function TSPlotComponents(U,S,V)
    A1 = S(1,1)*U(:,1)*V(:,1)';
    A2 = S(2,2)*U(:,2)*V(:,2)';
    plot(A1(1,:),A1(2,:),'r.');
    plot(A2(1,:),A2(2,:),'b.');
end
