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

조회 수: 43 (최근 30일)
BN
BN 2019년 10월 29일
편집: Adam Danz 2019년 10월 31일
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

채택된 답변

Fabio Freschi
Fabio Freschi 2019년 10월 29일
% 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
Stephen23
Stephen23 2019년 10월 31일
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)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Adam Danz
Adam Danz 2019년 10월 29일
편집: Adam Danz 2019년 10월 31일
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');

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by