create a variable based on timetable's date period

조회 수: 2 (최근 30일)
Sehoon Chang
Sehoon Chang 2020년 10월 1일
댓글: Star Strider 2020년 10월 1일
Hello dear advisors.
i wish to create a new variable (HP) for my timetable (TT) which datetime covers for multiple years.
For the periods in between 01.October till 30.April of each year available within the timetable, each timestamp shall get the value of 1 as a variable HP.
And as for the rest (01.May till 30.September), each remaining timestamps shall get the value of 0 as a variable of HP.
for example:
thanks!

채택된 답변

Star Strider
Star Strider 2020년 10월 1일
Try this:
DT = (datetime([2017 01 01]):caldays(1):datetime([2020 01 01])).'; % Create Dates
HP = ones(size(DT)); % Create ‘HP’
TT = timetable(DT,HP); % Create ‘timetable’
TF = [(TT.DT(day(TT.DT)==1 & month(TT.DT)==5)) (TT.DT(day(TT.DT)==30 & month(TT.DT)==9))]; % Starting & Ending Dates For All Years
for k = 1:size(TF,1)
TT.HP(TF(k,1) : TF(k,2),:) = 0; % Loop Through Years
end
Check = [TT(115:125,:); TT(270:280,:)]; % Check That It Works! (Delete Later)
CheckPlus1Yr = [TT((115:125)+365,:); TT((270:280)+365,:)]; % Check That It Works! (Delete Later)
Use the ‘TF’ matrix and the loop with your own timetable.
I called my datetime variable ‘DT’ to avoid using ‘datetime’ as a variable name.
The ‘Check’ lines show parts of the timetable demonstrating that this approach works. They are not otherwise a necessary part of the code, so delete them later.
  댓글 수: 2
Sehoon Chang
Sehoon Chang 2020년 10월 1일
thank you Star Strider,
you advices are great help!
Star Strider
Star Strider 2020년 10월 1일
As always, my pleasure!
Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2020년 10월 1일
편집: Steven Lord 2020년 10월 1일
Using the sample timetable Star Strider created:
DT = (datetime([2017 01 01]):caldays(1):datetime([2020 01 01])).';
HP = ones(size(DT));
TT = timetable(DT,HP);
Get the list of months for each row in the timetable:
M = month(TT.DT);
Determine which months are between May (5th month) and September (9th month) inclusive.
isInRangeFor0 = ismember(M, 5:9);
Create the new variable. Since isInRangeFor0 is true when we want the new variable to have value 0 and vice versa, we can just negate that variable.
TT.newvar = ~isInRangeFor0;
  댓글 수: 1
Star Strider
Star Strider 2020년 10월 1일
That’s definitely an interesting alternative.
Using ismember for the months didn’t occur to me. I’ll definitely keep that in mind!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by