How to use datetime as a condition in foor loop?

6 visualizaciones (últimos 30 días)
Luigi Romano
Luigi Romano el 5 de Sept. de 2020
Comentada: J. Alex Lee el 6 de Sept. de 2020
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 comentario
Stephen23
Stephen23 el 5 de Sept. de 2020
"...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.

Iniciar sesión para comentar.

Respuestas (1)

J. Alex Lee
J. Alex Lee el 5 de Sept. de 2020
Editada: J. Alex Lee el 5 de Sept. de 2020
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 comentarios
Stephen23
Stephen23 el 5 de Sept. de 2020
"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 el 6 de Sept. de 2020
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!

Iniciar sesión para comentar.

Categorías

Más información sobre Data Type Identification en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by