How to create a string with names that differ, without a loop?

11 ビュー (過去 30 日間)
Leonard Kluss
Leonard Kluss 2018 年 12 月 6 日
コメント済み: Guillaume 2018 年 12 月 6 日
I want
D_N = {'K1'; 'K2'; '...' ;'K9' ; '...'};
until Kn is reached with n equal to a parameter of my program (for example 39).
I can chose to use:
for ii = 1:39
D_N{ii} = sprintf('K%d', ii);
end
for ii = 1:39
D_N{ii} = ['K' num2str(ii)];
end
But is there a way without using this stupid loop?

採用された回答

Stephen23
Stephen23 2018 年 12 月 6 日
編集済み: Stephen23 2018 年 12 月 6 日
The fastest solution is to use the undocumented function sprintfc:
sprintfc('K%d',1:39)
As this is undocumented, use at your own risk. Otherwise arrayfun works, but feels like overkill:
arrayfun(@(n)sprintf('K%d',n),1:39,'uni',0)
As an alternative you could use the string data class and compose:
compose('K%d',1:39)
  1 件のコメント
Guillaume
Guillaume 2018 年 12 月 6 日
Since R2016b, there's absolutely no reason to use sprintfc and since it's undocumented, potentially disappearing in a future version, shouldn't be used at all.
compose doesn't require the use of the string class at all. compose produces a string array if the formatting string is of class string, and a cell array of char vectors if the formatting string is a char vector.
Always use compose or even easier the string composing functions as I've shown.

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

その他の回答 (1 件)

Guillaume
Guillaume 2018 年 12 月 6 日
compose works exactly that way:
D_N = compose('K%d', 1:39)
Another option is to use string arrays:
D_N = "K" + (1:39)
which are easier to work with than cell arrays of char arrays.
In versions of matlab without string arrays or compose (pre-R2016b), you can use the completely undocumented sprintfc instead:
D_N = sprintfc('K%d', 1:39)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by