How would I perform logical comparisons with times given in the form of a string vector?
조회 수: 2 (최근 30일)
이전 댓글 표시
I am given a vector of time values in "military time." I need to run through the entire vector and determine how many times are within a certain time window. How would I do this? Here's what I've tried so far:
temptime = IE322data{:,3};
time = datenum(temptime);
for j = 1:length(time)
if time(j) > datenum(6:00) & time(j) < datenum(14:00)
morningcount = morningcount + 1;
end
end
댓글 수: 1
답변 (2개)
Jan
2021년 4월 17일
편집: Jan
2021년 4월 17일
Are you sure that this is working:
temptime = IE322data{:,3};
What is the contents of IE322data ? The command works only, if this variable is a {1 x n} row cell. Then this would be more clear:
temptime = IE322data{1,3};
If is a cell array, you need round parentheses:
temptime = IE322data(:, 3);
The command datenum(6:00) replies an empty matrix, because 6:00 is same as 6:0, which is the empty matrix also. Even with quotes, I guess the command does not reply, what you want:
datenum('6:00')
% 738157.25
So this is 6 o'clock today. Now it would be useful to know, what the contents of your input data is. Are you searching for times at the current day? If not, maybe you want the fractional part only?
temptime = IE322data(:, 3);
time = datenum(temptime);
morningcount = sum(time > rem(datenum('6:00'), 1) & ...
time < rem(datenum('14:00'), 1));
Do you have a reason to work with the old datenum function instead of modern datetime objects?
Are you sure that "> 6:00" is wanted and not ">= 6:00"?
댓글 수: 0
Steven Lord
2021년 4월 17일
% time = datenum(temptime);
Instead of converting the dates and times to serial date numbers, I recommend converting them to a datetime array.
s = ["2021-04-17 12:15"; "2021-04-17 19:18"; "2021-04-18 02:01"; "2021-04-18 11:59"]
t = datetime(s)
Now you can use timeofday (if you don't care about the date information) and compare that with a duration.
start = hours(6);
finish = hours(19);
inrange = (start <= timeofday(t)) & (timeofday(t) <= finish)
Or if you had a timetable with these dates as the row times you could try a timerange.
Finally, if you want to bin the dates and times in t, you could do that with histcounts or histogram.
bins = datetime(2021, 4, 17):hours(6):datetime(2021, 4, 19);
histogram(t, bins)
[counts, binedges, binnumber] = histcounts(t, bins)
Element 2 of t is in the bin whose left edge is binedges(binnumber(2)).
fprintf('%s is in the range [%s, %s)\n', ...
string(t(2)), ...
string(binedges(binnumber(2))), ...
string(binedges(binnumber(2)+1)))
참고 항목
카테고리
Help Center 및 File Exchange에서 Calendar에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!