How to put variables into an array based on their values?
11 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Jaynik
on 7 Nov 2024 at 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 Comments
See Also
Categories
Find more on Whos 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!