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 Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by