string - How to find the closest time value to a given time value in matlab -
say have time value given, example: 2012-03-28_15:10:00
, have sting stores multiple time values:
2012-03-28_14:00:00 2012-03-28_14:10:00 2012-03-28_14:20:00 2012-03-28_14:30:00 2012-03-28_14:40:00 2012-03-28_14:50:00 2012-03-28_15:00:00 2012-03-28_15:05:00 2012-03-28_15:20:00 2012-03-28_15:30:00
i want find time value in string closest original time value. know how can done in matlab?
code
data1 = '2012-03-28_15:10:00' data2 = [ '2012-03-28_14:00:00' '2012-03-28_14:10:00' '2012-03-28_14:20:00' '2012-03-28_14:30:00' '2012-03-28_14:40:00' '2012-03-28_14:50:00' '2012-03-28_15:00:00' '2012-03-28_15:05:00' '2012-03-28_15:20:00'] [~,ind1] = min(abs(datenum(data2)-datenum(data1))); closest_time = data2(ind1,:)
output
closest_time = 2012-03-28_15:05:00
extended part: if have many dates, char matrix , compared list, using bsxfun
approach might better solution, avoids loops. shown below -
code
data1 = [ '2012-03-28_14:02:00' '2012-03-28_14:11:00' '2012-03-28_14:23:00' '2012-03-28_14:32:00'] data2 = [ '2012-03-28_14:00:00' '2012-03-28_14:10:00' '2012-03-28_14:20:00' '2012-03-28_14:30:00' '2012-03-28_14:40:00' '2012-03-28_14:50:00' '2012-03-28_15:00:00' '2012-03-28_15:05:00' '2012-03-28_15:08:00'] [~,ind1] = min(abs(bsxfun(@minus,datenum(data2),datenum(data1)'))); closest_time = data2(ind1,:)
output
closest_time = 2012-03-28_14:00:00 2012-03-28_14:10:00 2012-03-28_14:20:00 2012-03-28_14:30:00
Comments
Post a Comment