string join does not work for char arrays?

34 ビュー (過去 30 日間)
Leon
Leon 2020 年 8 月 28 日
コメント済み: Leon 2020 年 8 月 28 日
I have a column list of numbers like the below
M = [2; 3; 5; 7; 16];
What I want is to create a string array like this
"2, 3, 5, 7, 16"
Why can't I use the below to get what I want? What is the correct way to do this?
b = join(num2str(M), ', ')
Here is the error:
"First argument must be a string array, character vector, or cell array of character vectors."

採用された回答

Star Strider
Star Strider 2020 年 8 月 28 日
One approach:
M = [2; 3; 5; 7; 16];
M2Str = sprintf("%d, ",M(1:end-1)) + string(M(end))
producing:
M2Str =
"2, 3, 5, 7, 16"
.

その他の回答 (3 件)

Walter Roberson
Walter Roberson 2020 年 8 月 28 日
strjoin(string(M),', ')
or
strjoin(cellstr(num2str(M)),', ')
You could also consider
num2str(M.', '%g, ')
but that will leave an extra trailing comma
  1 件のコメント
Leon
Leon 2020 年 8 月 28 日
Many thanks! This is probably the cleanest way to do this.

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


Steven Lord
Steven Lord 2020 年 8 月 28 日
>> M = [2; 3; 5; 7; 16];
>> join(string(M), ", ")
ans =
"2, 3, 5, 7, 16"
num2str on M makes a char matrix which is not a "string array, character vector, or cell array of character vectors" and so is not a valid input to join. [Technically the error message should probably state 'character row vector', actually.]
  1 件のコメント
Leon
Leon 2020 年 8 月 28 日
Thank you. I didn't know it was as simple as that. I should use the function string instead of num2str.

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


Jeremy Perez
Jeremy Perez 2020 年 8 月 28 日
編集済み: Jeremy Perez 2020 年 8 月 28 日
Hi Leon,
Type:
help num2str
> num2str: Convert numbers to character representation.
You're not using strings but character arrays, which are different datatypes in MATLAB.
Try not to use character arrays as much as possible when you mean to use strings.
You can use:
join(string(M), ', ')
strjoin(string(M), ', ')
You can also test this:
sprintf('%d, ', M)
It'll add a comma at the end of your string that you can remove but it's a very useful function.
  1 件のコメント
Leon
Leon 2020 年 8 月 28 日
Thanks for the tips!

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by