3

Say that I have a time value given, for example: 2012-03-28_15:10:00 and then I have a sting that 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 to find the time value in the string that is the closest to the original time value. Does anyone know how this can be done in matlab?

user3366536
  • 151
  • 1
  • 2
  • 7
  • `2012-03-28_15:10:00` is a char array? What about the list, is that a char matrix? – Divakar Mar 24 '14 at 10:08
  • @Divakar Yes sorry, 2012-03-28_15:10:00 is a char array and the list is a char matrix. – user3366536 Mar 24 '14 at 10:14
  • I would do ´min(abs(t-t0))´, where ´t0´ is the one you want to find. If your time vectors are strings you should convert them first to a numerical format. – remus Mar 24 '14 at 10:17

1 Answers1

4

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 you have many dates, as a char matrix too and to be compared to the list, then using a bsxfun approach might be a better solution, as it avoids loops. This is 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
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • What's the advantage of using bsxfun instead of datenum(data2)-datenum(data1)? – remus Mar 24 '14 at 10:28
  • @remus You are right! `bsxfun` is an over-kill for this? :) – Divakar Mar 24 '14 at 10:30
  • @user3366536 Check out the `Extended Part` in the answer on why and where `bsxfun` might be "fun" :) – Divakar Mar 24 '14 at 10:46
  • 1
    @user3366536 Also it seems you haven't accepted some of your previous questions, including this one (if this has answered your question). Stackoverflow states this - `Accepting an answer is not meant to be a definitive and final statement indicating that the question has now been answered perfectly. It simply means that the author received an answer that worked for him or her personally..`. You may read more on this here - http://stackoverflow.com/help/accepted-answer – Divakar Mar 24 '14 at 11:32