How to find the common dates between two different variables that are not the same size or format?

19 views (last 30 days)
I have two different datetime arrays: dt which is (14782x1) and dt2 which is (47370x1). The formats between the two variables are also different where dt doesn't include minutes. For example, '9-Nov-2015 22:00:00'. While dt2 does include minutes so its like '9-Nov-2015 22:13:22'. I need to find the indexes where both variables have the same common time so I can plot other variables like wind speed. However, I'm having trouble getting the indexes. I've tried converting the two datetimes and using datenum and intersect but it doesn't really work. I've also tried ismember but depending on which variable I get first, I get two different sizes.
My code:
%get simultaenous data for ASCAT and HSRL
ff=datetime(dt2,'ConvertFrom','datenum'); %change format of ASCAT datenum so similar to HSRL format
%ff.Format = 'dd-MM-yyyy HH';
ff=datetime(ff,'InputFormat','dd-MMM-yyyy HH:mm:ss','Format','dd-MMM-yyyy HH');
%convert format of HSRL datetime
ff=datetime(ff,'InputFormat','dd-MMM-yyyy HH:mm:ss','Format','dd-MMM-yyyy HH');
%find the same times
The length of val and val2 end up being 25x1, however I know that there's more common datetimes just by scrolling through the variables.
Shayma Al Ali
Shayma Al Ali on 25 Oct 2021
Not in a table but the variables have the same lengths as the datetimes. So if I find the indexes of the datetimes, I can get the data I need from the other variables. And yes, ignoring the minutes and seconds.

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 25 Oct 2021
dtdt = datetime(dt, 'ConvertFrom', 'datenum', 'Format', 'dd-MMM-yyyy HH');
dtday = dateshift(dtdt, 'start', 'day');
%change format of ASCAT datenum so similar to HSRL format
dt2dt = datetime(dt2, 'ConvertFrom', 'datenum', 'Format', 'dd-MMM-yyyy HH');
dt2day = dateshift(dt2dt, 'start', 'day');
[common_dt, pos, pos2] = intersect(dtday, dt2day);

Scott MacKenzie
Scott MacKenzie on 25 Oct 2021
Edited: Scott MacKenzie on 25 Oct 2021
% load dt and dt2, as per question
load test
% ignore minutes and seconds
dt = dateshift(dt,'start','hour');
dt2 = dateshift(dt2,'start','hour');
% find common datetime values in dt and dt2 (ignoring minutes and seconds)
[dt3, idx] = intersect(dt, dt2);
dt3 and idx are 25x1 vectors, so your initial code was correct, but there is no need to work with datenum vectors


Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by