필터 지우기
필터 지우기

Writing a conditional statement for timeseries data

조회 수: 12 (최근 30일)
Benju Baniya
Benju Baniya 2022년 8월 18일
댓글: Walter Roberson 2022년 8월 30일
Hi,
In the code attached, I want to write a conditional statement based on datetime and sunrise sunset time. Sunrise is the sunrise time as character vector, sunrise_new is the sunrise time after converting it to HHMM format using datenum (but i am not sure which one to use). I want to figure out if it's a day or night based on datetime and sunrise sunset data. My code should read like:
If HH:MM value in DateTime is > sunrise & < sunset
time = 1
If HH:MM value in DateTime < sunrise & > sunset
time = 0
end
I don't know how to properly write conditional statement in matlab yet.

답변 (1개)

Rohit
Rohit 2022년 8월 22일
Hi,
In order to compare the times, you can use the "datenum()" function as shown in the below example:
% Getting current time
now=datetime('now')
now = datetime
22-Aug-2022 08:48:58
% Converting datetime to serial date number
format long
hour=now.Hour;
minn=now.Minute;
time_to_check=datenum(hour+":"+minn,'HH:MM')
time_to_check =
7.385223666666667e+05
sunrise = datenum('07:36', 'HH:MM' );
sunset = datenum('17:46', 'HH:MM' ) ;
% Conditional statement to figure out if it's a day or night
if time_to_check<sunrise || time_to_check>sunset
time=0;
else
time=1;
end
You can refer to the below Documentation link for "datenum" function along with the MATLAB Answers link:
  댓글 수: 2
Benju Baniya
Benju Baniya 2022년 8월 30일
Thank you. When I use the conditional statment, I get an error saying "Operands to the logical and (&&) and or (||) operators must be convertible to logical scalar values".
I used this code: Here joined_eddy is the merged file of provided dataet.
format = long
hour = joined_eddy.DateTime.Hour
min = joined_eddy.DateTime.Minute
time_to_check = datenum(hour+":"+ min, 'HH:MM')
%Day and night values
if time_to_check<joined_eddy.Sunrise || time_to_check>joined_eddy.Sunset
time = 0;
else
time = 1;
end
Walter Roberson
Walter Roberson 2022년 8월 30일
No loop needed, no datenum() needed
time = isbetween(joined_eddy.DateTime, joined_eddy.Sunrise, joined_eddy.Sunset, 'closed');

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

카테고리

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