How to locate the index of a certain date for a date-time array?
46 views (last 30 days)
Show older comments
Hello,
I have a date-time array, 'dt' that is recorded hourly for a whole year.
The first three data points are as follows, 01-Jan-2017 00:00:00, 01-Jan-2017 01:00:00, 01-Jan-2017 02:00:00.
I would like to find the index of every Monday(at 00:00:00) present in the data set . Below is what I have used, this is not feasable as I would need to know the exact date of every Monday, type it out row by row and save it to my matrix m.
m=zeros(52,1)
m(1)=find(datetime=='02-Oct-2017 00:00:00')
m(2)=find(datetime=='09-Oct-2017 00:00:00')
...
m(52)=find(datetime=='25-Dec-2017 00:00:00')
Is there a better way to do this?
What I am trying to achieve with this is to create new arrays that start on a Monday and last for a whole week, and do this for the span of a whole year.
I tried to use
[week,edges]=discretize(dt,"week")
but it does not start on a Monday, so I was not able to get it to work.
Thank you
0 Comments
Accepted Answer
Stephen23
on 10 Dec 2022
You are working with datetimes, so do not compare text!
dt = datetime(2017,1,1,(0:1:123).',0,0, 'Format','u MM dd eee HHmmss')
ix = timeofday(dt)==0 & weekday(dt)==2
md = dt(ix)
2 Comments
Stephen23
on 10 Dec 2022
"What I am trying to achieve with this is to create new arrays that start on a Monday and last for a whole week, and do this for the span of a whole year."
I would have answerd that, but your explanation is incomplete. It sounds as if you want to split your data into lots of separate arrays, but doing so is
- not a good use of MATLAB,
- means that you cannot use the inbuilt mehods for grouping and processing groups of data:
Instead of asking us about how to split data into lots of arrays, you should actaully ask us about your actual goal or task with that data:
More Answers (1)
Arif Hoq
on 10 Dec 2022
I don't have your data. try this one:
% creating datetime data from 1st January 2017 to 31 December 2017
firstdate = '01-01-2017 00:00:00';
t1 = datetime(firstdate,'InputFormat','dd-MM-yyyy HH:mm:ss');
lastdate='31-12-2017 23:00:00';
t2 = datetime(lastdate,'InputFormat','dd-MM-yyyy HH:mm:ss');
oneyeardata=t1:+hours(1):t2;
realdate=oneyeardata(:);
dayname=day(realdate,'name');
strname=string(dayname);
dateday=table(realdate,strname);
findmonday=find(strcmp(string(table2cell(dateday(:,2))),"Monday"));
idxmonday=dateday(findmonday,1);
aa=string(table2cell(idxmonday));
bb=split(aa," ");
cc=find(strcmp(bb(:,2),'00:00:00'));
Monday_Only=idxmonday(cc,1);
0 Comments
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!