randomly grouping cells in cell array

3 views (last 30 days)
so i have a cell array with names of people and i want to make a function that generate random groups out of those names.
i want to make it so that grouping{1} in main function would return first group randomly chosen
i have 22 people and if i want to separate into 6 groups, i want 4 groups of 4 people and 2 groups of 3 people.
i have a main function that defines cell array defined as Identifiers that contains all 22 people names as character.
i'm not sure how to use that Identifiers into this function below. this is how far i have. this only returns array with empty 6 cells like {1x4 double}.
function grouping = generate_random_grouping(number_of_people, number_of_groups)
randorder = randperm(number_of_people); %shuffle the people
split = repmat(floor(number_of_people / number_of_groups), 1, number_of_groups); %how many in each group?
toincrease = mod(number_of_people, number_of_groups); %how many groups need an extra element
split(1:toincrease) = split(1:toincrease) + 1;
grouping = mat2cell(randorder, 1, split);
end

Accepted Answer

Adam Danz
Adam Danz on 10 Oct 2019
Edited: Adam Danz on 11 Oct 2019
No need for a loop.
% create 22 names of people (just letters)
names = num2cell(char(97:118)); % {'a' 'b' 'c' ... 'v'}
number_of_people = numel(names);
number_of_groups = 6;
% Create random order of names
randOrder = randperm(numel(names));
namesPerm = names(randOrder);
% Determine number of people per group
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))];
% Create 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}
>>
% Convince yourself that the subgroups do not contain duplicates
% or missing names
numel(unique([nameGroups{:}])) == numel(names) %should equal 1 | true
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);
% Make it a column vector ^^^ ^^^^^^^^ switch those two inputs
  3 Comments
Adam Danz
Adam Danz on 11 Oct 2019
I updated my answer to allow for flexible group size. Also, at the bottom of the answer is a correction to your for-loop if you'd rather use the loop.
Kangkeon Jeon
Kangkeon Jeon on 12 Oct 2019
thank you so much! I understand now :))

Sign in to comment.

More Answers (0)

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!