Matrix math with Datetime arrays

7 ビュー (過去 30 日間)
Gabriel Stanley
Gabriel Stanley 2021 年 11 月 2 日
回答済み: Steven Lord 2021 年 11 月 3 日
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

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by