MATLAB Answers

0

timerange in a loop

Asked by Ugur Acar on 19 Oct 2019 at 19:40
Latest activity Commented on by Steven Lord
on 20 Oct 2019 at 12:40
is it possible to put dates into a loop used in timerange function?
for i=2012:2016;
s(i)=timerange('i-01-01','i-02-01')
end

  0 Comments

Sign in to comment.

Tags

3 Answers

Steven Lord
Answer by Steven Lord
on 20 Oct 2019 at 0:12
 Accepted Answer

Yes. Build datetime objects using the three-input syntax and use them to construct a timerange. I left off one of the semicolons in the example below so you can see that at each iteration a different timerange was built with a different year.
for theyear = 2012:2016
beginDate = datetime(theyear, 01, 01);
endDate = datetime(theyear, 02, 01);
TR = timerange(beginDate, endDate)
% Do something with TR
end

  3 Comments

Ugur Acar on 20 Oct 2019 at 7:36
building datetime objects works, thank you.
I got timetable TT with some missing data;
TT_int = retime(TT,'hourly','linear'); %Fill missing data using Linear interpolation
for i=2012:2016;
beginDate=datetime(i,01,01);
endDate=datetime(i,02,01);
TR=timerange(beginDate,endDate);
TT_january = TT_int(TR,:);
TT_mean=retime(TT_january,'daily','mean');
end
i did like this. but TT_mean timetablecreated just for the last year (2016),
i need the keep the data created for the other years also (2012-2013-2014-2015);
Ugur Acar on 20 Oct 2019 at 9:09
i guess i did it
for i=2012:2016;
beginDate=datetime(i,01,01);
endDate=datetime(i,02,01);
TR=timerange(beginDate,endDate);
TT_january = TT_int(TR,:);
TT_mean=retime(TT_january,'daily','mean');
for j=1:size(TT_mean,1);
TT_mean_jan(j,i-2011)=([TT_mean{j,1}]);
end
end
Steven Lord
on 20 Oct 2019 at 12:40
i did like this. but TT_mean timetablecreated just for the last year (2016),
Yes, that's correct. Each iteration through the loop you're overwriting the TT_mean variable.
i need the keep the data created for the other years also (2012-2013-2014-2015);
You could store it in a cell array, in a struct array, do whatever further processing you want to do on the January data inside the loop, or perhaps skip the timerange altogether and use groupsummary or grouptransform.

Sign in to comment.


Answer by Sulaymon Eshkabilov on 19 Oct 2019 at 20:06

Hi,
What about this:
for ii=2012:2016
H{ii-2011} = [num2str(ii), '-01-01',' : ', num2str(ii), '-02-01'];
end
Good luck.

  1 Comment

Ugur Acar on 19 Oct 2019 at 20:29
i tried this;
H{1} = [num2str(2012), '-01-01'];
H{2} = [num2str(2012), '-02-01'];
TR = timerange(H{1},H{2});
doesnt worked :(
timerange function works like that;
TR = timerange('2012-01-01','2012-02-01');
because of apostrophe may be.

Sign in to comment.


Answer by Sulaymon Eshkabilov on 19 Oct 2019 at 20:34

How about this way:
for ii=2012:2016
H{ii-2011,1} = [num2str(ii), '-01-01'];
H{ii-2011, 2}= [num2str(ii), '-02-01'];
end

  0 Comments

Sign in to comment.