How to sort by time

조회 수: 1 (최근 30일)
Kanakaiah Jakkula
Kanakaiah Jakkula 2017년 9월 16일
편집: dpb 2017년 9월 16일
Hi,
I have below data,I want to select two data points above and below to the specified time.
2015/8/5 12:13 2
2015/6/13 22:13 5
2015/9/16 15:45 8
2015/7/23 17:05 15
2015/9/14 12:45 20
2015/6/17 21:44 26
2015/5/13 12:45 28
given time is: 2015/7/23 17:05, two data counts above and below which are more close to give time are"
My desired output:
2015/8/5 12:13 2
2015/6/13 22:13 5
2015/9/14 12:45 20
2015/6/17 21:44 26
many many thanks in advance,

답변 (2개)

Andrei Bobrov
Andrei Bobrov 2017년 9월 16일
편집: Andrei Bobrov 2017년 9월 16일
T = readtable('20170916.txt','CollectOutput',1);
T.Var1 = strcat(T{:,1}(:,1),{' '},T{:,1}(:,2));
T.
t = datetime('2015/7/23 17:05','f','uuuu/MM/dd HH:mm')
z = abs(day(T{:,1} - t))
t = ~z;
y = ~t.*(cumsum(t) + 1 );
n = numel(z);
kk = (1:n)';
s = false(n,1);
for ii = 1:2
m = y == ii;
p = kk(m);
[~,v] = sort(z(m));
s(p(v(1:2))) = true;
end
out = T(s,:)
out =
4×2 table
Date data
________________ ____
2015/08/05 12:13 2
2015/06/13 22:13 5
2015/09/14 12:45 20
2015/06/17 21:44 26

dpb
dpb 2017년 9월 16일
편집: dpb 2017년 9월 16일
>> dnm=datetime(c(:,1),'format','yyyy/M/d HH:mm'); % convert date strings
>> target=datetime('2015/7/23 17:05','format','yyyy/M/d HH:mm'); % and the target date
>> [dnm,ix]=sort(dnm); % order, keep index
>> idx=[find(dnm<target,2,'last');find(dnm>target,2,'first')] % find closest two either side of target
idx =
2
3
5
6
>> c(ix(idx),:) % look up originals based on presort index
ans =
'2015/6/13 22:13' [ 5]
'2015/6/17 21:44' [26]
'2015/8/5 12:13' [ 2]
'2015/9/14 12:45' [20]
>>
Unlike the previous Answer this replaces, this doesn't assume the target time is identically one of those in the data vector (although that might be always so, this is more generic).
Also the previous note on sort wasn't so; not sure what was wrong that caused that symptom earlier...

카테고리

Help CenterFile Exchange에서 Linear and Nonlinear Regression에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by