How to add strings to an array within a loop

17 ビュー (過去 30 日間)
Sayan Banerjee
Sayan Banerjee 2020 年 11 月 18 日
コメント済み: Cris LaPierre 2020 年 11 月 18 日
Hello Team, I want to create an array of legend names for a plot. The final array should look like this:
legend_names = ["Case_1", "Case_2", Case_3", ......., "Case_30"]
So, I created a loop to create the variable names,
For ii=1:30
name = sprintf("Case_%d", ii); %%% to create the Case_X names
legend_names = append......?? %%% to create the array as mentioned before
end
Not sure how to construct the array in the loop.
Thanks for your help!

採用された回答

Cris LaPierre
Cris LaPierre 2020 年 11 月 18 日
If you are using strings, you can create this just using "+".
legend_names = "Case_" + string(1:5)
legend_names = 1×5 string array
"Case_1" "Case_2" "Case_3" "Case_4" "Case_5"
  2 件のコメント
Sayan Banerjee
Sayan Banerjee 2020 年 11 月 18 日
Thank you so much for the prompt response. Your method is amazing and works fine.
However, in the legend the underscore is interpreted as subscript. How to fix that?
Cris LaPierre
Cris LaPierre 2020 年 11 月 18 日
Set the tex interpreter to none.
legend(legend_names,'Interpreter',"none")

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

その他の回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 11 月 18 日
編集済み: Ameer Hamza 2020 年 11 月 18 日
Easier is to use compose()
legend_names = compose('Case_%d', 1:30)
It create a cell array which can be directly use with legend()
legend(legend_names)
You can also directly create a string array
legend_names = compose("Case_%d", 1:30)
  2 件のコメント
Sayan Banerjee
Sayan Banerjee 2020 年 11 月 18 日
Thank you so much for the prompt response. Your method is compact and works just to create the array.
However, in the legend the underscore is interpreted as subscript. How to fix that?
Ameer Hamza
Ameer Hamza 2020 年 11 月 18 日
Change the line to
legend_names = compose('Case\\_%d', 1:30)

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

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by