简体   繁体   English

如何在Matlab中找到最接近给定时间值的时间值

[英]How to find the closest time value to a given time value in matlab

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_15:10:00 ,然后有一个存储多个时间值的字符串:

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? 有人知道如何在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 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. 扩展部分:如果您有很多日期(也作为char矩阵并要与列表进行比较),则使用bsxfun方法可能是更好的解决方案,因为它避免了循环。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM