% calulation of the pcr estimator B with n components
%   written by: Chriss Grimholt, 3/5-2011

function B = principal_component_regression(X,Y,n)

n_max = rank(X);

if nargin < 3
    n = n_max;
end

if n > n_max
    fprintf('Number of components too high, using maximum components: %i\n', n_max)
    n = n_max;
end
    
    [u,s,v] = svd(X);
    
    u = u(:,1:n);
    s = s(1:n,1:n);
    v = v(:,1:n);
    
    for i = 1:size(diag(s))
        s(i,i) = inv(s(i,i));
    end
    
    B = Y*v*s'*u';

end