print numeric array as list with commas

49 ビュー (過去 30 日間)
lightroman
lightroman 2017 年 11 月 27 日
コメント済み: Dyuman Joshi 2024 年 2 月 25 日
I cant figure out how to print a = 1:10 as 1,2,3,4,5,6,7,8,9,10
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2024 年 2 月 25 日
(Assuming the values are integers which can be represented in double precision) With newer versions, you can use strings like this -
a = 1:10;
b = strjoin(string(a), ',')
b = "1,2,3,4,5,6,7,8,9,10"

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

採用された回答

Walter Roberson
Walter Roberson 2017 年 11 月 27 日
regexprep( mat2str(a), {'\[', '\]', '\s+'}, {'', '', ','})
or
[sprintf('%d,', a(1:end-1)), sprintf('%d', a(end))];
or
temp = sprintf('%d,', a);
temp(end) = []; %get rid of trailing comma
  1 件のコメント
lightroman
lightroman 2017 年 11 月 27 日
thanks! tricky..

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

その他の回答 (1 件)

CM
CM 2024 年 2 月 25 日
Here's one more possibillity in one line using strip:
a = 1:10;
sprintf("%s", strip(sprintf("%d,", a), ","))
% ans = "1,2,3,4,5,6,7,8,9,10"
It has the advantage that one can simultaneously add characters (like surrounding brackets) to the string formatting, control the number formatting (like decimal places), and use non-indexable input (like function calls), e.g.:
sprintf("[%s]", strip(sprintf("%.2f,", linspace(1,10,10)), ","))
% ans = "[1.00,2.00,3.00,4.00,5.00,6.00,7.00,8.00,9.00,10.00]"

カテゴリ

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