function [R R_v]= svdpca(dX,dX_v,maxrank)
%% applying PCA on the training set and projecting the test set onto PC subspace
% Input
%      dX: the training set
%      dX_v: the test set
%      maxrank: the number of PCs used in PCA
% Output
%      R: the score of the training set after PCA
%      R_v: the score of the test set after projection

[m1,n1] = size(dX);

DX = [dX;dX_v];
DcX = (DX - repmat(min(DX),size(DX,1),1))./(repmat(max(DX),size(DX,1),1)-repmat(min(DX),size(DX,1),1));

if size(DcX,2)>10000
     [U,S,V] = svd(DcX(1:m1,:),'econ');
else
    [U,S,V] = svd(DcX(1:m1,:)); 
end
a = diag(S).^2; k = 0;
for i = 1:maxrank
    k =k+1;
    s(i) = sum(a(1:k))/sum(a);
end
figure; hold; plot(s,'-o');
title('Variation of the cumulative variance with the number of PCs');
xlabel('Number of PCs'); ylabel('Cumulative variance (%)');

R = U(:,1:maxrank)*S(1:maxrank,1:maxrank);
R_v = DcX(m1+1:end,:)*V(:,1:maxrank);
R_v = (R_v - repmat(min(R_v),size(R_v,1),1))./(repmat(max(R_v),size(R_v,1),1)-repmat(min(R_v),size(R_v,1),1)); 
R = (R - repmat(min(R),size(R,1),1))./(repmat(max(R),size(R,1),1)-repmat(min(R),size(R,1),1)); 