Below the 10-fold cross validation loop coded myself, where data is normalized separately for training and test set.
There are 30 participants in the study, measured 8 times.
Label = 240 x 1 array. Predictor = 240 x 7 array.
10-fold cross validation makes 10 groups of 3 participants. FullCombs is the total number of unique combinations of 10 groups of 3 participants, without repetition.
ParInFold is a matrix that contains the unique combinations of 10 groups of 3 participants on each row, without repetition. This is to ensure that never the same 3 participants are grouped in a single fold more than once. (e.g., participant 1 2 and 3 are only in a fold together once. However, participant 1 and 2 can be in a fold with either participant 4, 5, 6 and onwards..)
AllParArray is a repeated array of the participant numbers 1:30 that corresponds to the repeated measure data. 30 participants, 8 conditions.
NumModels = 2;
NumFolds = 10;
idx = 1 : 3 : 30;
parfor nIter = 1 : FullCombs % Iteration over unique folds
Groups = ParInFold(nIter,:); % Grab line of unique grouping
cvIndices = NaN(length(AllParArray),1); % Allocate space to store grouping nums
tempLabel = NaN(NumFolds,NumModels);
for nFolds = 1 : NumFolds % Iterate to allocate group nums
if(nFolds<=NumFolds-1)
cvIndices(ismember(AllParArray,Groups(1,idx(nFolds):idx(nFolds+1)-1)),1)=nFolds;
else
cvIndices(ismember(AllParArray,Groups(1,idx(nFolds):end)),1)=nFolds;
end
end
for nFolds = 1 : NumFolds % Iterate over folds
Train = normalize(Predictor(cvIndices ~= nFolds,:)); % Grab training data
Test = normalize(Predictor(cvIndices == nFolds,:)); % Grab test data
for nModels = 1 : NumModels % Iterate over models
switch(nModels)
case 1
rng('default')
Mdl = fitclinear(Train,Label(cvIndices~=nFolds),'Learner','logistic','Cost',Cost,'Solver', 'bfgs','Regularization','ridge'); % Fit logistic classifier
case 2
rng('default')
Mdl = fitcsvm(Train,Label(cvIndices~=nFolds),'KernelFunction','RBF','KernelScale','auto','Standardize',false,'Cost',Cost); % Fit SVM classifier
end
tempLabel(cvIndices==nFolds,nModels) = predict(Mdl,Test); % store the predicted labels in a temp array for later storage into the full array label. This is to allow parallel processing.
end
end
label(nIter,:,:) = tempLabel;
end