フィルターのクリア

insert datetime in array

5 ビュー (過去 30 日間)
Trop Trader
Trop Trader 2024 年 2 月 27 日
コメント済み: Voss 2024 年 2 月 27 日
how can i insert datetime in the datetime array?
Example: insert 2008-03-28 in array
result: 2008-01-05 2008-02-02 2008-03-01 2008-03-28 2008-04-05 ........

採用された回答

Voss
Voss 2024 年 2 月 27 日
編集済み: Voss 2024 年 2 月 27 日
I assume the array is sorted and needs to remain sorted after inserting the new element.
One easy way is to concatenate the new element with the array and then sort that new array:
% a datetime array:
fmt = 'uuuu-MM-dd';
dt_array = datetime({'2008-01-05','2008-02-02','2008-03-01','2008-04-05'},'InputFormat',fmt)
dt_array = 1×4 datetime array
05-Jan-2008 02-Feb-2008 01-Mar-2008 05-Apr-2008
% a datetime scalar:
new_dt = datetime('2008-03-28','InputFormat',fmt)
new_dt = datetime
28-Mar-2008
% concatenate and sort:
dt_array = sort([dt_array new_dt])
dt_array = 1×5 datetime array
05-Jan-2008 02-Feb-2008 01-Mar-2008 28-Mar-2008 05-Apr-2008
  1 件のコメント
Voss
Voss 2024 年 2 月 27 日
Another more involved way is to find where the new element belongs in the array and insert it there:
% a datetime array:
fmt = 'uuuu-MM-dd';
dt_array = datetime({'2008-01-05','2008-02-02','2008-03-01','2008-04-05'},'InputFormat',fmt)
dt_array = 1×4 datetime array
05-Jan-2008 02-Feb-2008 01-Mar-2008 05-Apr-2008
% a datetime scalar:
new_dt = datetime('2008-03-28','InputFormat',fmt)
new_dt = datetime
28-Mar-2008
% make sure the array is sorted
if ~issorted(dt_array)
% and sort it if not
dt_array = sort(dt_array);
end
% find the index of the first element of dt_array later than new_dt
idx = find(dt_array > new_dt, 1);
% if there are no elements later than new_dt
if isempty(idx)
% then new_dt goes on the end
idx = numel(dt_array)+1;
end
% insert dt_new at index idx in dt_array
dt_array = [dt_array(1:idx-1) new_dt dt_array(idx:end)]
dt_array = 1×5 datetime array
05-Jan-2008 02-Feb-2008 01-Mar-2008 28-Mar-2008 05-Apr-2008

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Distribution Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by