randomly grouping cells in cell array
조회 수: 1 (최근 30일)
이전 댓글 표시
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
채택된 답변
Adam Danz
2019년 10월 10일
편집: Adam Danz
2019년 10월 11일
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
Adam Danz
2019년 10월 11일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!