difference between str2num and str2double for getting a matrix

6 ビュー (過去 30 日間)
Yash Phirke
Yash Phirke 2020 年 11 月 22 日
編集済み: Bruno Luong 2020 年 11 月 22 日
>> txt = '5 7; 8 9';
>> f = str2num(txt)
f =
5 7
8 9
>> f = str2double(txt)
f =
NaN
So I have a text of that form with semi-colon and spaces and the str2num() is doing a very good job in getting me a 2x2 matrix, which is what I need and it has saved me a lot of hassle.
But the software recommended to use str2double() as it has got high precission or something like that. So, my doubt is-
1) Why isn't it working like str2num() here?
2) What is the actual difference between them ?
3) Should I stick with str2num() in this case?

採用された回答

Bruno Luong
Bruno Luong 2020 年 11 月 22 日
編集済み: Bruno Luong 2020 年 11 月 22 日
Under the hood
  • str2num uses EVAL
  • str2double uses SCANF, and work only on scalar.
I see no reason why SCANF is more accurate than EVAL. Both are limited by the digit number that is stored in string.
Now some people will tell you EVAL is evil. Honestly I don't care if it translates your string data directly to vector/matrix then it does the job and just use it.
Personally I use str2double if I know I want a scalar, it can be more rigorous error checking, all other case I use str2num.
I would be happy for someone to teach me otherwise.
  2 件のコメント
Steven Lord
Steven Lord 2020 年 11 月 22 日
Just keep in mind the story of Bobby Tables if you're using str2num.
Bruno Luong
Bruno Luong 2020 年 11 月 22 日
編集済み: Bruno Luong 2020 年 11 月 22 日
>> str = 'system(''echo "I remember BOB TABLE"'')';
>> x = str2num(str)
"I remember BOB TABLE"
x =
0
>>

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by