randomly grouping cells in cell array
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Kangkeon Jeon
am 10 Okt. 2019
Kommentiert: Kangkeon Jeon
am 12 Okt. 2019
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
0 Kommentare
Akzeptierte Antwort
Adam Danz
am 10 Okt. 2019
Bearbeitet: Adam Danz
am 11 Okt. 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 Kommentare
Adam Danz
am 11 Okt. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Sparse Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!