How to get the index from a datetime array corresponding to a time duration?
조회 수: 16 (최근 30일)
이전 댓글 표시
Hi I am trying to get the starting and ending index from a datetime array that corresponds to a specific time duration.
Find below my code for a general datetime array
t1 = datetime('23-Feb-2015 09:43:08')
num=2000
t2 = t1 + seconds(1:num)
I am interested in getting the starting and ending index from t2 with a time step durations of 5min.
index1=starting and ending index from t2 which corresponding to first 5 min.
index2=starting and ending index from t2 which corresponding to next 5 min .
.
.
.
index= starting and ending index from t2 which corresponds to remaining time.
I tried something using "minutes" but i do not know how to access the starting and ending index from t2. Can you please help?
댓글 수: 1
K E
2016년 11월 8일
I am also having trouble trying to get the index to datetime objects that are later than a certain time. I wish Matlab would expand its examples on using datetime to include this, and other kinds of 'time math' operations.
답변 (2개)
Steven Lord
2016년 11월 8일
start = datetime('now');
vec = start + hours(0:24).'; % datetime + duration = datetime
midnight = dateshift(start, 'end', 'day');
pastMidnight = vec > midnight; % relational operators work
T = table(vec, pastMidnight)
The first element of the pastMidnight variable inside the table T (or the logical vector pastMidnight) that is true should be the first time in the vec variable inside the table T (or the datetime array vec) that is past midnight. I didn't need to display the information as a table, but I feel it formats the data nicely.
Logical indexing also works.
vec(pastMidnight)
If you are storing your data in a timetable, the retime method and indexing using withtol or timerange objects may be of interest or use to you.
댓글 수: 0
Peter Perkins
2016년 11월 9일
There are many ways to do this, I bet. Here's one:
>> bin = floor((t2 - t1) ./ minutes(5)) + 1;
>> i2 = [find(diff(bin)>0) length(bin)+1];
>> i1 = [1 i2(1:end-1)+1];
>> [i1; i2]
ans =
1 300 600 900 1200 1500 1800
299 599 899 1199 1499 1799 2001
In general, with arbitrary time points or bin size, you'd proably want to substitute discretize for floor(...) to avoid any round-off issues, but with whole seconds and whole minutes there is no issue.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!