フィルターのクリア

How can I make a string array consisting of strings with numerical suffixes?

2 ビュー (過去 30 日間)
재훈
재훈 2022 年 11 月 23 日
コメント済み: Stephen23 2022 年 11 月 24 日
I want to make a 50x1 array that consists of 'sub01', ‘sub02’, ‘sub03’, ‘sub04’, …, ‘sub50’.
And this is my code, but it doesn't work
Sub=[];
for i=1:50
Sub(i,1) = str2num("sub%2d",i);
end
Error using str2num
Incorrect number of arguments. Each parameter name must be followed by a corresponding value.
Please help me ☹️

回答 (2 件)

Cris LaPierre
Cris LaPierre 2022 年 11 月 23 日
編集済み: Cris LaPierre 2022 年 11 月 23 日
str2num won't work with a word ("sub"). It's also unnecessary if you are using sprintf.
One other correction I would make is in how you preallocate your array. The empty brackets initializes your variable Sub as a double, so all strings will appear as NaN. You need to initiallize as an empty string.
Try something like this.
Sub = strings;
for i=1:50
Sub(i,1) = sprintf("sub%02d",i);
end
% view result
Sub
Sub = 50×1 string array
"sub01" "sub02" "sub03" "sub04" "sub05" "sub06" "sub07" "sub08" "sub09" "sub10" "sub11" "sub12" "sub13" "sub14" "sub15" "sub16" "sub17" "sub18" "sub19" "sub20" "sub21" "sub22" "sub23" "sub24" "sub25" "sub26" "sub27" "sub28" "sub29" "sub30"
  2 件のコメント
Cris LaPierre
Cris LaPierre 2022 年 11 月 23 日
Not quite the same result, but if you don't care about the leading 0, here's another way to do this.
Sub = "sub" + (1:50)'
Sub = 50×1 string array
"sub1" "sub2" "sub3" "sub4" "sub5" "sub6" "sub7" "sub8" "sub9" "sub10" "sub11" "sub12" "sub13" "sub14" "sub15" "sub16" "sub17" "sub18" "sub19" "sub20" "sub21" "sub22" "sub23" "sub24" "sub25" "sub26" "sub27" "sub28" "sub29" "sub30"
재훈
재훈 2022 年 11 月 24 日
Thank you ;)

サインインしてコメントする。


Walter Roberson
Walter Roberson 2022 年 11 月 23 日
compose("sub%02d",1:50).'
  2 件のコメント
재훈
재훈 2022 年 11 月 24 日
Thank you ;)
Stephen23
Stephen23 2022 年 11 月 24 日
+1 very neat

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by