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!