zesy
zesy

Reputation: 481

Find specific date in a date array

I am working with a datetime array s constructed as follows:

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

I am using ismember function to find the first occurrence of a specific date in that array.

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

The two lines from above are called many times in my application and consume quite some time. It is clear to me that Matlab compares ALL dates from s with specificDate, even though I need only the first occurrence of specificDate in s. So to speed up the application it would be good if Matlab would stop comparing specificDate to s once the first match is found.

One solution would be to use a while loop, but with the while loop the application becomes even slower (I tried it).

Any idea how to work around this problem?

Upvotes: 2

Views: 3019

Answers (2)

gnovice
gnovice

Reputation: 125874

I'm not sure what your specific use-case is here, but with the step size between elements of s being one hour, your index is simply going to be the difference in hours between your specific date and the start date, plus one. No need to create or search through s in the first place:

startPlace = hours(specificDate-ds)+1;

And an example to test each solution:

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!

Upvotes: 1

Murad Omar
Murad Omar

Reputation: 90

What you can do to save yourself some time is to convert the datetime to a datenum in such a case you will be comparing numbers rather than strings, which significantly accelerates your processing time, like this:

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

Upvotes: 1

Related Questions