Matrix math with Datetime arrays

9 views (last 30 days)
I have a function for determining the element in Array 1 which is closest to a given element in Array 2, developed form this question & answer chain. However, when I attempt to input datetime arrays, the segment [Array2.'-Array1] throws an error stating that the inputs have to be the same size, which is not a fault thrown when I feed the code differently-sized numeric arrays. I would use time2num to convert the datetime arrays, however that function does not allow for the level of precision I require (less than seconds).
Are there any known work-arounds for performing matrix math on datetime arrays or, failing that, any other ideas on how to convert datetimes to numeric values at arbitrary precisions?

Accepted Answer

Steven Lord
Steven Lord on 3 Nov 2021
Support for implicit expansion for certain operations on datetime, duration, calendarDuration, and categorical arrays was added in release R2020b.
If upgrading is not an option, you could use repmat to convert the vectors of different orientation into matrices with the same dimensions and perform the elementwise operations on those matrices.

More Answers (1)

Kelly Kearney
Kelly Kearney on 3 Nov 2021
As you discovered, implicit expansion of is only supported for numerical arrays (though I'm not sure where that's documented.) To do the same with datetimes, I would just convert to datenumbers:
t1 = datetime(2021,1:12,1);
t2 = datetime(2021,1,1) + days(rand(10,1)*365);
dt = datenum(t1) - datenum(t2); % pairwise difference in days (numeric array)
You can always cast back to durations if you need to do time-oriented stuff after that:
dt = days(dt); % duration array

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!