How to create an array and fill it by these values using loop ?
10 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Fabio Freschi
il 29 Ott 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 Commento
Stephen23
il 31 Ott 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)
Più risposte (1)
Adam Danz
il 29 Ott 2019
Modificato: Adam Danz
il 31 Ott 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');
Vedere anche
Categorie
Scopri di più su String Parsing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!