Extend a cell array of dates (from days only, to hours and days) in a compact way
이전 댓글 표시
I have a cell vector containing 44 dates, i.e. days:
>> C
ans =
44×1 cell array
{'17-Jun-2017'}
{'18-Jun-2017'}
{'19-Jun-2017'}
...
{'28-Jul-2017'}
{'29-Jul-2017'}
{'30-Jul-2017'}
I would like to "extend" that cell vector to include the 24 hours as well, in each day.
This means that my cell vector will pass from 44 elements (i.e. the 44 days) to 24 * 44 = 1056 elements (i.e. 24 hours in each day). Something like this:
% Desired Output (something like this)
>> D
ans =
1056×1 cell array
{'17-Jun-2017 00:00:00'}
{'17-Jun-2017 01:00:00'}
{'17-Jun-2017 02:00:00'}
...
{'17-Jun-2017 23:00:00'}
{'18-Jun-2017 00:00:00'}
{'18-Jun-2017 01:00:00'}
{'18-Jun-2017 02:00:00'}
...
{'29-Jul-2017 23:00:00'}
{'30-Jul-2017 00:00:00'}
Any idea on how to do it in a compact way ?
Maybe there is a simple in-built function in Matlab to do that, and that I am probably missing right now..
채택된 답변
추가 답변 (3개)
Mitch Lautigar
2022년 5월 17일
1 개 추천
Use for loops. Here's an untested example of what I mean.
stack_array = [];
for i = 1:length(C)
curr_date = C(i);
for j = 1:24
stack_array = [stack_array;cell(strjoin(cellstr(curr_date),'-',num2str(j)) )];
end
end
In theory, this code would loop through and for every date in your C loop, add in the hours with a dash in the middle to keep the formatting you have above. Hope it helps!
댓글 수: 2
Mitch Lautigar
2022년 5월 17일
1 개 추천
stack_array = [stack_array;cell(strjoin(cellstr(curr_date),'-',num2str(j)) )]; should be:
stack_array = [stack_array; cell(strjoin(cellstr(curr_date),'-',num2str(j),'') )]; forgot to tell strjoin how to join the command.
I'd probably take advantage of implicit expansion for datetime and duration arrays, introduced for those types in release R2020b.
C = {'17-Jun-2017'; '18-Jun-2017'; '19-Jun-2017'}
theDays = datetime(C).'
theHours = hours(0:23).'
D = theDays + theHours; % Adding a row vector and a column vector gives a matrix
D = reshape(D, [], 1)
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!