function [coeffs,maxRidgeParamIndex]=kFoldRidge(data,kin,k,ridgeParams)
% kFoldRidge does a k-fold Crossvalidation of parameter lambda for Ridge
% Regression
    if any(size(ridgeParams)>1)
        
        correlationPerParam=zeros(size(ridgeParams));
        
        for param=ridgeParams
            
            randomMapping=transpose(randperm(size(data,1)));
            correlations=zeros(k,1);

            parfor i=1:k
                %split into training and test set
                trainData=data(mod(randomMapping,k)+1~=i,:);
                testData=data(mod(randomMapping,k)+1==i,:);
                trainKin=kin(mod(randomMapping,k)+1~=i);
                testKin=kin(mod(randomMapping,k)+1==i);
                
                coeffs=ridge(trainKin,trainData,param,0);
                correlations(i)=ridgeCorrelation(testData,testKin,coeffs);
            end
            % use mean correlation as correlation for the current parameter
            correlationPerParam(ridgeParams==param)=mean(correlations);
        end
        [~,maxRidgeParamIndex]=max(correlationPerParam);
    else
        maxRidgeParamIndex=1;
    end
    coeffs=ridge(kin,data,ridgeParams(maxRidgeParamIndex),0);
end