Extract rows from a matrix using time ranges
4 次查看(过去 30 天)
显示 更早的评论
Hello everyone, i have a problem. I have to extract rows from a matrix using time ranges (each row between those dates), for example
mi matrix look like,
A=734139 2 1.2
734140 3 1.4
734141 10 0.4
734142 8 0.1
734143 14 2.1
734144 20 4.3
734145 1 5.1
734146 2 3.1
734147 3 2.1
734148 2 1.3
And i have other matrix with time ranges for example (initial date and final date of ranges):
B= 734139 734141
734145 734145
I expect have this
C= 734139 2 1.2
734140 3 1.4
734141 10 0.4
734145 1 5.1
734146 2 3.1
I know how did it with the new time tools (like timetables for example).. in fact is done, but i must use only basic tools because i'm translatting this code for old products (matlab2012a specifically) and octave.
Thank you for your help!
0 个评论
采纳的回答
Rik
2019-5-8
I'm going to assume your last element of B should be 1 larger, because then your C makes sense. The code below should do what you need by looping over your different time segments.
A= [734139 2 1.2
734140 3 1.4
734141 10 0.4
734142 8 0.1
734143 14 2.1
734144 20 4.3
734145 1 5.1
734146 2 3.1
734147 3 2.1
734148 2 1.3];
B= [734139 734141
734145 734146];
row=false(size(A,1),1);
t_=A(:,1);
for k=1:size(B,1)
t1=B(k,1);t2=B(k,2);
row=row | (t_>=t1 & t_<=t2);
end
C=A(row,:);
clc
fprintf('%6d %02d %3.1f\n',C')
更多回答(1 个)
Peter Perkins
2019-5-8
dulio, I strongly recommend that you use datetims and timetables. You will likely be happier in the long run:
>> X = [734139 2 1.2
734140 3 1.4
734141 10 0.4
734142 8 0.1
734143 14 2.1
734144 20 4.3
734145 1 5.1
734146 2 3.1
734147 3 2.1
734148 2 1.3];
>> t = array2table(X,'VariableNames',{'Date' 'X' 'Y'});
>> t.Date = datetime(t.Date,'ConvertFrom','datenum','Format','dd-MMM-yyyy');
>> tt = table2timetable(t)
tt =
10×2 timetable
Date X Y
___________ __ ___
01-Jan-2010 2 1.2
02-Jan-2010 3 1.4
03-Jan-2010 10 0.4
04-Jan-2010 8 0.1
05-Jan-2010 14 2.1
06-Jan-2010 20 4.3
07-Jan-2010 1 5.1
08-Jan-2010 2 3.1
09-Jan-2010 3 2.1
10-Jan-2010 2 1.3
>> dt = datetime([734139 734141],'ConvertFrom','datenum')
dt =
1×2 datetime array
01-Jan-2010 00:00:00 03-Jan-2010 00:00:00
>> tr = timerange(dt(1),dt(2))
tr =
timetable timerange subscript:
Select timetable rows with times in the half-open interval:
[01-Jan-2010 00:00:00, 03-Jan-2010 00:00:00)
See Select Timetable Data by Row Time and Variable Type.
>> tt1 = tt(tr,:)
tt1 =
2×2 timetable
Date X Y
___________ _ ___
01-Jan-2010 2 1.2
02-Jan-2010 3 1.4
3 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!