How would I perform logical comparisons with times given in the form of a string vector?
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Risposte (2)
Jan
il 17 Apr 2021
Modificato: Jan
il 17 Apr 2021
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 Commenti
Steven Lord
il 17 Apr 2021
% 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)))
Vedere anche
Categorie
Scopri di più su Calendar in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!