What's the difference between the function string() and num2str() ?

27 ビュー (過去 30 日間)
JONG MIN LEE
JONG MIN LEE 2018 年 9 月 21 日
回答済み: Walter Roberson 2018 年 9 月 21 日
num2str() looks like "number to string"
but It seems to be a lot different from what I think.
>>> [string(3.14), 'pi']
1×2 string Array
ans =
"3.14" "pi"
>>> [num2str(3.14), 'pi']
ans =
'3.14pi'
Can anyone explain this difference?
I use matlab version R2018b, academic

採用された回答

Walter Roberson
Walter Roberson 2018 年 9 月 21 日
string() creates string objects, which are arrays, each entry of which can contain an individual text string. There are a number of functions defined to work with these string objects. They have some useful properties, such as
"abc" + (1:3)
ans =
1×3 string array
"abc1" "abc2" "abc3"
The individual entries are not character vectors: the individual entries are 1 x 1 string objects. But you can convert scalar string objects to character vectors using {} indexing.
string objects are sort of like defining some nice operations on cellstr (cell array of character vectors)
string() applied to a numeric value converts the numeric value to a string object using decimal conversion. The format rules are not publicly defined, and are not consistent with any of the defined "format" properties. There is no control over how string() converts numeric values to string objects, no ability to pass in a format specification.
int2str() rounds numeric values to integers and converts the result to decimal representation of integers. Character arrays are returned. No options are available. Internally int2str() uses sprintf()
num2str() converts numeric values to decimal representation. Character arrays are returned. Options are available to indicate the number of decimal places to use or to specify a format. num2str() goes through trouble with 2D arrays to be sure to line up each column to produce a nice displayable table. Internally num2str() uses sprintf()
There is also the undocumented sprintfc() which converts numeric values to decimal representation. A cellstr (cell array each entry being a character vector) is returned. Inputs are a format specification and a single array (not multiple arguments like for sprintf() )

その他の回答 (0 件)

カテゴリ

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