sprintf: how to efficiently create a string of 75 numbers, separated by comma

3 ビュー (過去 30 日間)
Abhinav
Abhinav 2018 年 4 月 27 日
編集済み: Stephen23 2018 年 4 月 27 日
I have an array which contains 75 numeric elements. I want to write these numbers as a string separated by a comma. If there were few numbers, I could use 'sprintf' as follows:
A=[1,2];
str=sprintf('%d,%d',A(1:end));
I need an efficient way to do it when there are many entries in A.

採用された回答

Star Strider
Star Strider 2018 年 4 月 27 日
You can still use sprintf. You just need to create a ‘dynamic’ format string:
A = 1:5;
str = sprintf([repmat('%d,',1, numel(A)-1), '%d'], A)
str =
'1,2,3,4,5'
That will adapt for any ‘A’ vector.
  2 件のコメント
Abhinav
Abhinav 2018 年 4 月 27 日
Thanks a lot!
Star Strider
Star Strider 2018 年 4 月 27 日
As always, my pleasure!

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

その他の回答 (2 件)

Ameer Hamza
Ameer Hamza 2018 年 4 月 27 日
編集済み: Ameer Hamza 2018 年 4 月 27 日
This will work.
strjoin(string(A), ',')
  2 件のコメント
Walter Roberson
Walter Roberson 2018 年 4 月 27 日
Note: this requires R2016b or later. Also, it creates a string object output, not a character vector.
Ameer Hamza
Ameer Hamza 2018 年 4 月 27 日
Thanks for elaborating.

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


Stephen23
Stephen23 2018 年 4 月 27 日
編集済み: Stephen23 2018 年 4 月 27 日
"I need an efficient way to do it when there are many entries in A."
This is probably about the most efficient way:
A = 1:5;
str = sprintf(',%d',A);
str = str(2:end);
Timing comparisons for 1e4 iterations:
Elapsed time is 0.539053 seconds. % this answer.
Elapsed time is 2.54425 seconds. % Star Strider's answer.
  2 件のコメント
Walter Roberson
Walter Roberson 2018 年 4 月 27 日
I didn't answer -- I commented on someone else's answer.
Stephen23
Stephen23 2018 年 4 月 27 日
編集済み: Stephen23 2018 年 4 月 27 日
@Walter Roberson: you are right, sorry for the confusion. I fixed the reference.

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

カテゴリ

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