How to create an array and fill it by these values using loop ?

43 views (last 30 days)
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

Accepted Answer

Fabio Freschi
Fabio Freschi on 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 Comment
Stephen23
Stephen23 on 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)

Sign in to comment.

More Answers (1)

Adam Danz
Adam Danz on 29 Oct 2019
Edited: Adam Danz on 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');

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!