creating new variable using for loop and if-else condition

7 ビュー (過去 30 日間)
Arturo Jr. Ongkeko
Arturo Jr. Ongkeko 2020 年 12 月 12 日
コメント済み: Arturo Jr. Ongkeko 2020 年 12 月 12 日
Hi,
I wish to divide my age data in column vector into age-groups 10-29, 20-29, 30-39, 40-49, 50-59, etc. using for loop and the if-else statements. here what I have started. but i wonder how to create that new variable age group.
for n=1:length(age)
if age(n)==10 & age(n)<=29
new_age_group1 = age() <what to place here>
elseif age(n)==30 & age(n)<=39
new_age_group2 = age() <what to place here>
end
end

採用された回答

madhan ravi
madhan ravi 2020 年 12 月 12 日
age = 1 : 40; % you were almost close, note: it could be done without loops
[new_age_group1, new_age_group2] = deal(cell(40, 1));
for n = 1 : numel(age)
if age(n) >= 10 && age(n) <= 29;
new_age_group1{n} = age(n);
elseif age(n) >= 30 && age(n) <= 39
new_age_group2{n} = age(n);
end
end
new_age_group1 = cat(1, new_age_group1{:})
new_age_group1 = 20×1
10 11 12 13 14 15 16 17 18 19
new_age_group2 = cat(1, new_age_group2{:})
new_age_group2 = 10×1
30 31 32 33 34 35 36 37 38 39

その他の回答 (1 件)

Geoff Hayes
Geoff Hayes 2020 年 12 月 12 日
Arturo - look closely at your conditions
if age(n)==10 & age(n)<=29
The above would mean that nth element of the age array is identical (==) to 10 and less than or equal to (<=) 29. This will only be true when age(n) is 10. Instead try
if age(n) >= 10 && age(n) <= 29
where age(n) is at least 10 and at most 29. You will need to do something similar for your other condition. As for grouping the ages, you might want to use a cell array where each element is an array of those ages that fit the condition. For example,
age_group = cell(5,1);
for n=1:length(age)
if age(n)>=10 && age(n)<=29
age_group(1) = [age_group{1} age(n)];
elseif age(n)>=30 && age(n)<=39
age_group(2) = [age_group{2} age(n)];
end
end
  1 件のコメント
Arturo Jr. Ongkeko
Arturo Jr. Ongkeko 2020 年 12 月 12 日
Thanks very much Geoff! I get really confuse with loops and if-else so I am trying to be comfortable with it by implementing it in every opportunity I could even if there are other ways to do it. I want to develop my logic too in using these and the way you explain it really helped me a lot!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by