If and elseif with Or

5 views (last 30 days)
kathy
kathy on 3 Nov 2017
Commented: kathy on 3 Nov 2017
I would like to distinguish id2 if we encounter a leap year. However, this current code sets id2 to true for values(days) 32 through 60 for nonleap years as well, so the elseif isn't working properly.
function mmean_Feb_year=mmean_Feb_(year,file)
T = readtable(file);
M =table2array(T);
id1 = M(:,1)==year;
dmean_year = M(id1,:);
if year==2008||2012||2016
id2 = dmean_year(:,2)>=32 & dmean_year(:,2)<=60;
elseif year==2007||2009||2010||2011
id2 = dmean_year(:,2)>=32 & dmean_year(:,2)<=59;
end
dmean_Feb_year = dmean_year(id2,:);
mmean_Feb_year = mean(dmean_Feb_year(:,3:end),'omitnan');
end
I also tried the following, but this did not save the leap year id2, and made id2 true for days 32-59 for all years.
function mmean_Feb_year=mmean_Feb_(year,file)
T = readtable(file);
M =table2array(T);
id1 = M(:,1)==year;
dmean_year = M(id1,:);
if year==2008||2012||2016
id2 = dmean_year(:,2)>=32 & dmean_year(:,2)<=60;
end
if year==2007||2009||2010||2011
id2 = dmean_year(:,2)>=32 & dmean_year(:,2)<=59;
end
dmean_Feb_year = dmean_year(id2,:);
mmean_Feb_year = mean(dmean_Feb_year(:,3:end),'omitnan');
end

Accepted Answer

KL
KL on 3 Nov 2017
Edited: KL on 3 Nov 2017
when you use | |, you should use it like,
if year == 2012 || year == 2016 % and so on
you need have "an expression" on both side of the | |.
when you write
if year == 2012 || 2016
it checks the first part of the condition (year==2012) but the second part is simply a number which is not zero, so the condition becomes true. So based on what you wrote, the condition becomes always true.
  1 Comment
kathy
kathy on 3 Nov 2017
Oh! My apologies for the silly mistake. Thank you!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!