How to delete certain rows of a table based on time

I have minute by minute data for gold prices, and need to delete rows that are not in the time range 8:25-9:00. The data goes throughout the entire day, before going to the next day (so the rows deleted are not all together). Any idea on how to do this? I have attached a picture of my data table.

 Accepted Answer

h = hour(yourtable.DateTime);
m = minute(yourtable.DateTime);
filteredtable = yourtable((h == 8 & m >= 25) | (h == 9 & m ==0), :)

2 Comments

Guillaume:
When I run that, I am getting the following error message:
Error using datevec (line 217) Failed to lookup month of year.
Error in hour (line 37) c = datevec(d(:));
Any ideas on what to do about this?
Oh! So, your DateTime column is not of type datetime. Kind of a misleading name!
d = datetime(yourtable.DateTime) %you may need to specify an 'InputFormat'
%optional: to change DateTime to an actual datetime
%yourtable.DateTime = d;
h = hour(d);
m = minute(d);
filteredtable = yourtable((h == 8 & m >= 25) | (h == 9 & m ==0), :)
There's really no reason to use the old datestr or datenum format. datetime is a lot more flexible and powerful.

Sign in to comment.

More Answers (1)

Another similar way:
>> eightTwentyFive = duration(8,25,0)
eightTwentyFive =
duration
08:25:00
>> nineOClock = duration(9,0,0)
nineOClock =
duration
09:00:00
>> d = datetime(2018,2,22,8,0:15:1500,0)
d =
1×101 datetime array
22-Feb-2018 08:00:00 22-Feb-2018 08:15:00 22-Feb-2018 08:30:00 22-Feb-2018 08:45:00 22-Feb-2018 09:00:00
[snip]
>> tod = timeofday(d)
tod =
1×101 duration array
08:00:00 08:15:00 08:30:00 08:45:00 09:00:00 [snip]
>> (eightTwentyFive <= tod) & (tod < nineOClock)
ans =
1×101 logical array
Columns 1 through 29
0 0 1 1 0 0 0 [snip]

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!