Formatted string plus list of numbers using sprintf

I would like to display comma-separated records like the following,
Record1,2,8,3,5,2,6,3,7,7,7
Here's my attempt, but is there a less clunky way?
% Make the record label string
iRecord = 1;
strLabel = ['Record' num2str(iRecord)];
% Make the number vector
numberList = round(rand(1,10)*10);
% Turn number vector into a string
numberListIntoString = sprintf('%d,', numberList);
% Remove comma at end
numberListIntoString = numberListIntoString(1:(end-1));
% Display the result
disp([strLabel ',' numberListIntoString])

 採用された回答

Adam Danz
Adam Danz 2019 年 6 月 18 日

0 投票

numberList = round(rand(1,10)*10);
s = ['Record',regexprep(num2str([1,numberList]),' +',',')];

3 件のコメント

Adam Danz
Adam Danz 2019 年 6 月 18 日
BTW, another way to create a vector of random integers between 0 and 10:
randi(11,1,10)-1
KAE
KAE 2019 年 6 月 18 日
編集済み: KAE 2019 年 6 月 18 日
I was unfamiliar with regexprep, so thanks. Just for my own learning on regular expressions, here we construct a string using
num2str([1,numberList]) % Space-separated list of numbers, with record number first
The spaces are replaced multiple times ('+') with commas.
Adam Danz
Adam Danz 2019 年 6 月 18 日
num2str([1,numberList])
That line adds more than 1 space between each number. The ' +' in the regular expression means search for at least one or more consecutive spaces.
Just for learning, remove that plus sign and see what happens,
numberList = round(rand(1,10)*10);
s = ['Record',regexprep(num2str([1,numberList]),' ',',')];
% ^ only 1 space

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2019 年 6 月 18 日
編集済み: Steven Lord 2019 年 6 月 18 日

1 投票

If you're using a release that supports string convert your numeric vector into a string using string. Next use join to combine the elements of that string array into one string, each separated by a delimeter. Finally concatenate the result to the end of a header string with +. I separated the steps into four lines for clarity, but you could do it in one.
vec = [1 2 8 3 5 2 6 3 7 7 7]
strvec = string(vec)
str = join(strvec, ',')
S = "Record " + str
I chose to separate "Record" and the first element of the the vector with a space; remove the last character of the string in the last line if you don't want that.

1 件のコメント

KAE
KAE 2019 年 6 月 18 日
I have 2019a, so string is supported (since 2016b).

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

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2019a

質問済み:

KAE
2019 年 6 月 18 日

コメント済み:

2019 年 6 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by