Matrix math with Datetime arrays

6 次查看(过去 30 天)
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?

采纳的回答

Steven Lord
Steven Lord 2021-11-3
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.

更多回答(1 个)

Kelly Kearney
Kelly Kearney 2021-11-3
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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by