function [B,U1,S1,V1,T,P]=mypcr(Y,X,im);
% MYPCR 
% [B,U1,S1,V1,T,P]=mypcr(Y,X,im);
% PURPOSE
% An SVD implementation of PCA and PCR.
% ON INPUT
% im INTEGER
%            im = 1: works on the normal equation X'*Y = X'*X*B + X'*E
%            im = 2: works directly on Y = X*B + E
% NOTE:
% im=1 is to be preferred when the number of samples N is large compared
% to the number of X variables nr where [N,nr]=size(X).

[N1,nr]=size(X); [N2,nm]=size(Y); N=max(N1,N2);
X=X(1:N,:); Y=Y(1:N,:);

%% 1. Foerste del, SVD.
if im == 1         % Tar utgangspunkt i  normalligningen X'*Y = X'*X*B + X'*Y.
 XX = X'*X; 
 Y  = X'*Y;
 [U S V]=svd(XX);
else               % Tar utgangspunkt direkte i Y = X*B + E.
 [U S V]=svd(X);
end

%% 2. PCA, finner antall uavhengige variable ved innspeksjon av sv-ene.
si=diag(S(1:nr,1:nr))
r=nr;
r = fchan('Number of principal components ?',r);

%% 3. PCR 
U1=U(:,1:r); 
S1=S(1:r,1:r); 
V1=V(:,1:r);
B = V1*pinv(S1)*U1'*Y;          % Matrix of regression coefficients.
T = U1*S1;                      % Score vector matrix for X.
P = V1;                         % Loading vector matrix for X.