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!