Extend a cell array of dates (from days only, to hours and days) in a compact way
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Star Strider
le 17 Mai 2022
Modifié(e) : Star Strider
le 17 Mai 2022
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 commentaires
Plus de réponses (3)
Mitch Lautigar
le 17 Mai 2022
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 commentaires
Mitch Lautigar
le 17 Mai 2022
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
le 17 Mai 2022
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)
Voir également
Catégories
En savoir plus sur Dates and Time dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!