How to put variables into an array based on their values?

조회 수: 11 (최근 30일)
Dacoda Davis
Dacoda Davis 2019년 12월 28일
답변: Jaynik 2024년 11월 7일 7:49
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.

답변 (1개)

Jaynik
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!

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by