在日期数组中查找特定日期

时间:2017-05-24 16:19:11

标签: arrays matlab datetime

我正在使用如下构造的日期时间数组df = df.filter(df.col_X. isNotNull())

s

我正在使用ismember函数来查找该数组中特定日期的第一次出现。

ds = datetime(2010,01,01,'TimeZone','Europe/Berlin');
de = datetime(2030,01,01,'TimeZone','Europe/Berlin');
s = ds:hours(1):de;

上面的两行在我的应用程序中被多次调用并消耗了相当长的时间。我很清楚Ma​​tlab会将ind = ismember(s,specificDate); startPlace = find(ind,1); s的所有日期进行比较,即使我只需要在specificDate中首次出现specificDate。因此,为了加速应用程序,一旦找到第一个匹配项,Matlab将停止将sspecificDate进行比较,这将是一件好事。

一种解决方案是使用while循环,但使用while循环,应用程序变得更慢(我尝试过)。

知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我不确定您的具体用例是什么,但是s元素之间的步长是一小时,您的索引就是您的特定日期和开始日期加一。无需首先创建或搜索s

startPlace = hours(specificDate-ds)+1;

测试每个解决方案的示例:

specificDate = datetime(2017, 1, 1, 'TimeZone', 'Europe/Berlin');  % Sample date

ind = ismember(s, specificDate);  % Compare to the whole vector
startPlace = find(ind, 1);        % Find the index

isequal(startPlace, hours(specificDate-ds)+1)  % Check equality of solutions

ans =

  logical

   1        % Same!

答案 1 :(得分:1)

你可以做些什么来节省你自己的时间是将日期时间转换为datenum,在这种情况下你将比较数字而不是字符串,这会显着加快你的处理时间,如下所示:

s_new = datenum(s);
ind = ismember(s_new,datenum(specificDate)); 
startPlace = find(ind,1);