MATLAB: How to use “if statements” when “ismember” is based on multiple conditions

for loopif statementloops

I have two vectors:
indexM = csvread('indexM.csv'); %228 obs
indexI = csvread('indexI.csv'); %199 obs
indexM is a vector where every row indicates a row index for variables at monthly frequency from 2002 to 2020, while indexI is a vector where every row denotes a row index for variables at an irregular frequency from 2002 to 2020.
We can see this by doing:
% monthly dates
tM = datevec(datetime(indexM, 'ConvertFrom', 'datenum'));
tM(:,1) = vertcat(repmat(2002,1,12)', repmat(2003,1,12)', repmat(2004,1,12)', repmat(2005,1,12)', repmat(2006,1,12)', repmat(2007,1,12)', repmat(2008,1,12)', repmat(2009,1,12)', repmat(2010,1,12)', repmat(2011,1,12)', repmat(2012,1,12)', repmat(2013,1,12)', repmat(2014,1,12)', repmat(2015,1,12)',repmat(2016,1,12)',repmat(2017,1,12)',repmat(2018,1,12)',repmat(2019,1,12)',repmat(2020,1,12)');
tM= tM(:,1:3);
tM= datetime(tM);
% irregulare dates
tI = datevec(datetime(indexI, 'ConvertFrom', 'datenum'));
tI(:,1) = vertcat(repmat(2002,1,11)', repmat(2003,1,12)', repmat(2004,1,11)', repmat(2005,1,11)', repmat(2006,1,11)', repmat(2007,1,11)', repmat(2008,1,12)', repmat(2009,1,12)', repmat(2010,1,12)', repmat(2011,1,12)', repmat(2012,1,12)', repmat(2013,1,12)', repmat(2014,1,12)', repmat(2015,1,8)',repmat(2016,1,8)',repmat(2017,1,8)',repmat(2018,1,8)',repmat(2019,1,8)',repmat(2020,1,8)');
tI= tI(:,1:3);
tI = datetime(tI);
Now, what I want to do is writing a loop that says: whenever tI and tM have the same month and year, indexM equals indexI. I wrote this loop as follows:
rr = [];
for i = 1:length(indexM)
if ismember(month(tM(i)) & year(tM(i)), month(tI) & year(tI)) == 1 % if A is found in B
rr(i) = indexM(i);
else
rr(i) = NaN;
end
end
However, what I got back rr is simply indexM. This happens since ismember doesn't find any zero values and this is weird. In fact, for example:
% tI(8) : 11-Sep-2002
% tM(8) : 30-Aug-2002
% which would have meant filling the 8th row of rr with Nan
What am I doing wrong?
Thanks!

Best Answer

Your syntax is not correct. Split your condition into 2 separate uses of ismember. Also, ismember returns a value for every element of the second input. Use any to return the single logical result an if statement needs. Since the result is logical, you do not have to compare the result to 1.
I think something like this is what you want (untested)
if any(ismember(month(tM(i)), month(tI))) & any(ismember(year(tM(i)),year(tI)))