function MSE=KfoldCV(X,Z, K,lambda,a,weights)

[~,T]=size(X);
t=floor(T/K);
nLambdas = length(lambda);

if nargin > 5
    parfor k=1:K
        test = zeros(T,1);
        if k==K
            test(1+(k-1)*t:end) = 1; test = logical(test);
        else
            test(1+(k-1)*t:k*t) = 1; test = logical(test);
        end
        
        XTest = X(:,test); ZTest = Z(:,test);
        XTrain = X(:,logical(1-test)); ZTrain = Z(:,logical(1-test));
        
        ATrain = adaptiveElasticNet(XTrain,ZTrain,lambda,a,weights);
        
        for j=1:nLambdas
            resTest = XTest-ATrain(:,:,j)*ZTest;
            SE(k,j) = mean(diag(resTest'*resTest));
        end
    end
else
    parfor k=1:K
        test = zeros(T,1);
        if k==K
            test(1+(k-1)*t:end) = 1; test = logical(test);
        else
            test(1+(k-1)*t:k*t) = 1; test = logical(test);
        end
        
        XTest = X(:,test); ZTest = Z(:,test);
        XTrain = X(:,logical(1-test)); ZTrain = Z(:,logical(1-test));
        
        ATrain = adaptiveElasticNet(XTrain,ZTrain,lambda,a);
        
        for j=1:nLambdas
            resTest = XTest-ATrain(:,:,j)*ZTest;
            SE(k,j) = mean(diag(resTest'*resTest));
        end
    end
end

MSE = mean(SE,1);
