필터 지우기
필터 지우기

How to use datetime as a condition in foor loop?

조회 수: 12 (최근 30일)
Luigi Romano
Luigi Romano 2020년 9월 5일
댓글: J. Alex Lee 2020년 9월 6일
Hallo,
I have a dataset for a whole year and I would like to separate the year into seasons. I have a table like this one
yyyy-mm-dd daytime temperature
'2019-01-01' 0 '7.2'
'2019-01-01' 0,0416666666666667 '8.5'
'2019-01-01' 0,0833333333333333 '8.3'
'2019-01-01' 0,125000000000000 '7.3'
'2019-01-01' 0,166666666666667 '7.2'
'2019-01-01' 0,208333333333333 '6.9'
where the type of the first column is datetype and I have extracted the second and third columns that are now columns of doubles, let's say DayTime= str2double(A(:,2)) and Temp=str2double(A(:,3)).
I cannot just count the number of hour per day since some data have been measured 24/24 in some days but only 2-3 times on some other days. So I wanted to implement something like in the code below, but of course is not working since I cannot use the operator == with datetime. Any suggestion?
Temp_january = [];
for i=1:length(Temp)
if A(i,1) == '2019-01-dd'
Temp_January = [Temp_January; Temp(i)]
end
end
  댓글 수: 1
Stephen23
Stephen23 2020년 9월 5일
"...of course is not working since I cannot use the operator == with datetime."
Why not? All logical comparison operators support the datetime class:
>> datetime(2020,9,5)==datetime('2020-09-05')
ans =
1
According to the datetime documentation they even work when one input is datetime and one is char. Lets try it:
>> datetime(2020,9,5)=='2020-09-05'
ans =
1
Wow... there must be some fancy overloading going on there! I am not a fan of implicit type conversion, but I have to admit that that is quite impressive.
Note that your code uses '2019-01-dd', which is not a valid date string, therefore it cannot be implictly converted and will throw an error.

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

답변 (1개)

J. Alex Lee
J. Alex Lee 2020년 9월 5일
편집: J. Alex Lee 2020년 9월 5일
i believe you can, you just have coded it as a comparison of a datetime to a string.
A(i,1) == datetime(2019,1,dd)
  댓글 수: 2
Stephen23
Stephen23 2020년 9월 5일
"you just have coded it as a comparison of a datetime to a string."
Actually a character vector, which according to the eq documentation is valid for comparing with datetime.
J. Alex Lee
J. Alex Lee 2020년 9월 6일
oh that's neat...frivolous but neat...and i just committed possibly the most frustrating thing i have found in recent matlab: referring to character vectors as strings...oops!

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

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by