How to use datetime as a condition in foor loop?

5 ビュー (過去 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 Center および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by