No need for a loop.
names = num2cell(char(97:118));
number_of_people = numel(names);
number_of_groups = 6;
randOrder = randperm(numel(names));
namesPerm = names(randOrder);
groupNum = floor(number_of_people / number_of_groups) + [ones(1,rem(number_of_people,number_of_groups)), zeros(1,number_of_groups - rem(number_of_people,number_of_groups))];
groupIdx = [0,cumsum(groupNum)];
nameGroups = arrayfun(@(i){namesPerm(groupIdx(i)+1:groupIdx(i+1))},1:numel(groupNum));
nameGroups is a cell array of 6 groups
nameGroups =
1×6 cell array
{1×4 cell} {1×4 cell} {1×4 cell} {1×4 cell} {1×3 cell} {1×3 cell}
>>
numel(unique([nameGroups{:}])) == numel(names)
To use your loop instead, all you need to do is switch around some of the inputs in mat2cell(). This function drives me crazy sometimes.
grouping = mat2cell(randorder(:), split, 1);
Best Answer