假设我有一个时间值,例如: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
我想在字符串中找到最接近原始时间值的时间值。 有谁知道在matlab中如何做到这一点?
答案 0 :(得分:3)
<强>代码强>
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,:)
<强>输出强>
closest_time =
2012-03-28_15:05:00
扩展部分:如果您有许多日期,作为字符矩阵并与列表进行比较,那么使用bsxfun
方法可能是更好的解决方案,因为它避免了循环。如下所示 -
<强>代码强>
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,:)
<强>输出强>
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