MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

2

Why 'str2double' is preferred over 'str2num?

Sachin Ganjare さんによって質問されました 2012 年 10 月 30 日
Many times while writting matlab code, matlab forces to use 'str2double' function instead of 'str2num'.
I searched a lot, but could not get a convincing answer. Anyobody here has any idea?

  0 件のコメント

サインイン to comment.

3 件の回答

回答者: Walter Roberson
2012 年 10 月 30 日
 採用された回答

MATLAB does not force one to use str2double(), but mlint may recommend it.
>> str2num('sqrt(pi)')
ans =
1.77245385090552
Did you really want people to be able to enter arbitrary text and have it executed by MATLAB ?

  2 件のコメント

Andrei Bobrov
2012 年 10 月 30 日
>> cs = {'125' '.258' '12.36' '-2.369'}
cs =
'125' '.258' '12.36' '-2.369'
>> str2num(cs)
Error using str2num (line 33)
Requires string or character array input.
>> str2double(cs)
ans =
125 0.258 12.36 -2.369
>>
Sachin Ganjare 2012 年 10 月 31 日
Thanks Walter & Andrei.

サインイン to comment.


Jan
回答者: Jan
2012 年 10 月 30 日

STR2MUM evaluates the string using EVAL. Therefore there might be unexpected side effects:
str2num('system(''format C:''); fprintf(''9\n'')');

  1 件のコメント

Sachin Ganjare 2012 年 10 月 31 日
Thank You Jan.

サインイン to comment.


回答者: Daniel Shub
2012 年 10 月 30 日

In this case I think it is best to actually look at the code of the two functions
type str2num
type str2double
One problem with str2num is that it uses EVAL. A malicious user could therefore cause major problems if str2num is used. That said, the use of eval within str2num is one of those cases where it is well encapsulated and unlikely to cause problems (but as I will point out below, can still lead to unexpected outcomes). It will in general be slow, but often that is not a big deal.
The real advantage is that str2double is a lot more powerful. It can handle all sorts of representations of numbers. For example, str2double can handle 1,000, while str2num cannot. In fact, str2num does not give you an error, but rather [1, 0], which might be unexpected.

  1 件のコメント

Sachin Ganjare 2012 年 10 月 31 日
Thanks Daniel.

サインイン to comment.



Translated by