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.)
.
更多回答(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!