How to create an array and fill it by these values using loop ?
38 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
how to creating a 480*1 single array (not datetime) and fill it this way:
1982-01-01
1982-02-01
1982-03-01
1982-03-01
1982-04-01
.
.
.
2015-12-01
(it does not matter if even there is only text)
I don't know how to do it, please help in this issue. thank you all
0 commentaires
Réponse acceptée
Fabio Freschi
le 29 Oct 2019
% intialization and preallocation
k = 1;
date = strings(480,1); % string array
for i = 1982:2015
for j = 1:12
% concat string
date(k) = strcat(num2str(i),'-',num2str(j,'%02d'),'-01');
% display strings
fprintf('%s\n',date(k));
% increment
k = k+1;
end
end
1 commentaire
Stephen23
le 31 Oct 2019
Rather than this complex group of commands:
strcat(num2str(i),'-',num2str(j,'%02d'),'-01')
Simpler to use one sprintf call:
sprintf('%d-%02d-01',i,j)
Plus de réponses (1)
Adam Danz
le 29 Oct 2019
Modifié(e) : Adam Danz
le 31 Oct 2019
Why use a loop?
ds = datestr(datenum(1982, 01, 01) + cumsum([0;ones(479,1)]),'yyyy-mm-dd');
Result: (first 5 rows)
ds(1:5,:)
ans =
5×10 char array
'1982-01-01'
'1982-01-02'
'1982-01-03'
'1982-01-04'
'1982-01-05'
[Addendum]
On second thought, this is simpler and avoids cumsum()
ds2 = datestr(datenum(1982, 01, 01) + (0:479).','yyyy-mm-dd');
Voir également
Catégories
En savoir plus sur String Parsing 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!