To clean up the main code of the cross-validation script, I decided to source out the part that deals with splitting the data into training and testing sets. After I had created and verified the code, I discovered Matlab’s built-in dividevec function from the Neural Network Toolbox. It does something similar and was introduced from R2006A:

The dividevec function facilitates dividing your data into three distinct sets to be used for training, cross validation, and testing, respectively. Previously, you had to split the data manually.


However, here’s my own code for documentation purposes:
% function partly adapted from
% http://neuralnetworks.ai-depot.com/NeuralNetworks/1281.html
%
% use for splitting a matrix (horizontally) into subsets
% for cross-validation
%
% takes a matrix A as input and two numbers:
% i: total number of cross-validation subsets
% i_th: which of the i cross-validation subset should be generated
%
% returns a TrainSet and a TestSet
%---
% by russ@iws.cs.uni-magdeburg.de
% 2007-10-22
%---

function [TrainSet TestSet] = splitCV(A, i, i_th)
rows = size(A,1);
% size for each block. The last block will be used for padding.
blocksize = round(rows/i);
% as long as we're into the upper blocks of the data,
% take their full size
if i_th < i
TrainSet = [A(1:(i_th-1) * blocksize,:); A(1+(i_th * blocksize):end,:)];
TestSet = A((1+(i_th-1) * blocksize):(i_th * blocksize),:);
% otherwise take the remainder of the data
else
TrainSet = A(1:(i_th-1) * blocksize,:);
TestSet = A((1+(i_th-1) * blocksize):end,:);
end