How to change date in a for loop?

4 views (last 30 days)
I am working in a for loop and inside the loop it looks as follows:
format shortg
c=clock;
display(c);
c_fc = c+[0 0 0 4 0 0]; %addition for weather forecast in hours or days
%only if 4 hour forecast is being done. change the parameters
%(date or hours)accordingly
if c(4)< 20;
c_fc(4)=c_fc(4);
else if c(4)==20;
c_fc(4)=0;
c_fc(3)=c_fc(3)+1;
else if c(4)== 21;
c_fc(4)=1;
c_fc(3)=c_fc(3)+1;
else if c(4)==22;
c_fc(4)=2;
c_fc(3)=c_fc(3)+1;
else if c(4)==23;
c_fc(4)=3;
c_fc(3)=c_fc(3)+1;
end
end
end
end
end
%making a search query for real time and forecast data
search=sprintf('%d-%0.2d-%0.2dT%0.2d:00:00Z',c(1:4));
search_fc=sprintf('%d-%0.2d-%0.2dT%0.02d:00:00Z',c_fc(1:4));
I need to make a search_fc which takes the values from weather website for that time period. I could update the hours and date with if and else if loop. but how can I make it shorter and also incorporate change in month and year so that my code can keep on running.

Accepted Answer

Kelly Kearney
Kelly Kearney on 9 Apr 2015
Not quite sure I understand the question, but you can definitely simplify that code significantly. If I understand it correctly, c_fc is simply a datevector 4 hours after c, right? So then,
c = clock;
fcspan = 4/24; % 4 hours, converted to days
c_fc = datevec(datenum(c) + fcspan);
That will take care of any complications with changing days, and you can change the forecast span and start date however you want.
  1 Comment
Punit Gandhi
Punit Gandhi on 9 Apr 2015
Thank you. yes it changes the date for c_fc. I think it will be able to change month and year automatically as well now.

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!