Extend a cell array of dates (from days only, to hours and days) in a compact way
조회 수: 2 (최근 30일)
이전 댓글 표시
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..
댓글 수: 0
채택된 답변
Star Strider
2022년 5월 17일
편집: Star Strider
2022년 5월 17일
Try this —
C1 = {'17-Jun-2017'; '30-Jul-2017'}
DT1 = [datetime(C1{1}) : days(1) : datetime(C1{end})]'
DT2 = [min(DT1): hours(1) : max(DT1)]'
C2 = compose('%s',string(DT2))
It simply creates a new datetime vector with a different increment from the original cell array, and then uses the compose function to create a new cell array from that. (I would keep it as a datetime array rather than converting it back to a cell array.)
.
댓글 수: 7
추가 답변 (3개)
Mitch Lautigar
2022년 5월 17일
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일
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.
Steven Lord
2022년 5월 17일
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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!