0

This is my code

 for i= 1:length(t)
    h(i)=t(i)
    if % condition here??
        myfunction(h)        
    end 
end

t is a date array like:

   2009-05-07
   2010-05-09
   2011-05-16
   2012-05-21
   2014-05-24
   2016-05-27
   2016-05-31

I want to make an if test or something that makes dates before 2011 not go into the function.

1
  • 2
    are your dates strings or datetime? Commented May 30, 2017 at 9:58

2 Answers 2

2

If your t is in datetime format, you can use the year property:

for ii = 1:length(t)
    h = t(ii);
    if year(h) >= 2011
        myfunction(h);      
    end 
end

You can shorten the loop by testing all of the dates at once, this will be much quicker than doing an if check for every date:

t_after2011 = t(year(t) >= 2011);
for ii = 1:length(t_after2011)
    myfunction(t_after2011(ii));
end

If it is a cell array of strings, you can convert it to datetime first using t_datetime = datetime(t);

Sign up to request clarification or add additional context in comments.

Comments

0

Convert your dates to date vectors using datevec. Now you can access the years from this vectors and put your condition.

str = {'2009-05-07'
   '2010-05-09'
   '2011-05-16'
   '2012-05-21'
   '2014-05-24'
   '2016-05-27'
   '2016-05-31'} ;
vec = datevec(str) ;

for i = 1:size(str,1)

    if vec(i,1)>2011
        disp(str{i}) ;
    end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.