Search code examples
matlabmatlab-figure

Extracting specific time points from two different time vectors in MATLAB


I have two time vectors:

V1 = ['02-Feb-2018 08:23:42' '02-Feb-2018 08:24:42'.... '02-Feb-2018 09:10:42']
V2 = [' 8:35 AM' ' 8:36 AM'...' 9:01 AM'].

Now, I want to identify the indices of starting (t0) and ending point (tend) of V2 (in this case t0 = '8:35 AM' and tend = '9:01 AM') in V1 and initialize a vector V3 (of length V1) which contains '1' between t0 and tend, and '0' in other time points. Since v1 and V2 are in different formats, i am not sure how to use datestr here. Below is the code which works if both V2 is the same format as V1:

V1=['02-Feb-2018 08:23:42'; '02-Feb-2018 08:24:42';'02-Feb-2018 09:10:42'];
V2 = [' 8:35 AM' ;' 8:36 AM';' 9:01 AM'];
V1=datenum(V1);
V2=datenum(V2);
[~,t0]=min(abs(V2(1)-V1));
[~,tend]=min(abs(V2(end)-V1));

Solution

  • I'd recommend utilizing datetime rather than datenum here. While datenum could be made to work, using datetime provides us with a much more helpful set of methods and allows us to more easily normalize the values of V2 to the date of V1. One approach takes the dates from V1 and assigns them to V2, which allows for direct logical comparisons using the start and end times.

    For example:

    V1 = ["02-Feb-2018 08:23:42"; "02-Feb-2018 08:24:42"; "02-Feb-2018 08:45:15"; "02-Feb-2018 09:10:42"];
    V2 = ["8:35 AM"; "8:36 AM"; "9:01 AM"];
    
    % Convert to datetime
    d1 = datetime(V1);
    d2 = datetime(V2, 'InputFormat', 'hh:mm a');  % Will assign today for date
    
    % Assume all dates in V1 & V2 are the same
    [y, m, d] = ymd(d1(1));  % Extract year, month, day from d1
    [d2.Year, d2.Month, d2.Day] = deal(y, m, d);  % Set date of d2 to that of d1
    
    % Find min/max of d2
    t_0 = min(d2);
    t_end = max(d2);
    
    % Generate V3
    V3 = zeros(size(V1));
    V3((d1 >= t_0 & d1 <= t_end)) = 1;
    

    Which returns:

    >> V3.'
    
    ans =
    
         0     0     1     0
    

    As expected.

    Note that I've added a timestamp to V1 that falls within the time window generated by V2, which your original example doesn't have. I've also used arrays of strings (introduced in R2016b) to avoid having to whitespace pad a character array. If you're using an older version of MATLAB you should use a cell array instead.