How to put variables into an array based on their values?
11 次查看(过去 30 天)
显示 更早的评论
Hello,
Someone was telling me about a problem at work which involves placing kids into classes, which can essentially be done at random but their are multiple exceptions based on kids not being able to be in some of the same classes together for behavioral reasons.
Basically I thought I could make a pretty simple code where I assign variables (names) integer values and place them arrays based on those values. So, for example, array one would have a list of kids that are assigned that value 1.
The problem is, I'm not sure how to produce arrays based on variable values. Was thinking of possibly using an if statement but couldn't figure it out.
0 个评论
回答(1 个)
Jaynik
2024-11-7,7:49
Hi Dacoda,
The strategy suggested by you should work. You can create a cell array of kids and numeric array for values that represent behavior. Then you can use logical indexing to directly index into an array based on a condition. Here is a sample code for the same:
kids = {'Alice', 'Bob', 'Charlie', 'David', 'Eve'};
values = [1, 2, 1, 3, 2];
group1 = kids(values == 1);
group2 = kids(values == 2);
group3 = kids(values == 3);
disp(group1);
disp(group2);
disp(group3);
If statements can also be used as you had mentioned. We can do the following:
group1 = {};
group2 = {};
group3 = {};
for i = 1:length(kids)
if values(i) == 1
group1{end+1} = kids{i};
elseif values(i) == 2
group2{end+1} = kids{i};
elseif values(i) == 3
group3{end+1} = kids{i};
end
end
Hope this helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!