What's difference between str2num and str2double for converting an array to numeric values?
조회 수: 71 (최근 30일)
이전 댓글 표시
Hi, I have a 'char' array and want to convert it to a numeric array. when I use the function
str2num
I get the following error:
"Error using str2num (line 35)
Input must be a character vector or string scalar."
but I can change the format of the array using
str2double
can someone tell me why does the latter work?
댓글 수: 5
Walter Roberson
2021년 8월 3일
str2num() will not work with cell array of character vectors.
str2double() will work with cell array of character vectors.
str2num() will work with char array with multiple rows.
str2double() will not work with char array with multiple rows.
채택된 답변
Vignesh Murugavel
2021년 8월 4일
str2num(chr) converts a character array or string scalar to a numeric matrix. The input can include spaces, commas, and semicolons to indicate separate elements. If str2num cannot parse the input as numeric values, then it returns an empty matrix.
The str2num function does not convert cell arrays or nonscalar string arrays, and is sensitive to spacing around + and - operators.
str2num() contains a call to eval(), which means that if your string has the same form as an array (e.g. with semicolons) then it is simply executed and the resulting array is returned. The problems with str2num() are that it doesn’t support cell arrays, and that because it uses an eval() function, wierd things can happen if your string includes a function call. str2double() is supposedly faster as well. So the general rule seems to be, use str2double() unless you are wanting to convert a string array of numbers to a numerical array.
There is one catch though- if you are converting a single number from a string to a number, then it would SEEM like str2num() and str2double() are interchangable, drop in replacements. However, if the string is not a number, they behave differently
댓글 수: 1
Stephen23
2021년 8월 4일
"...unless you are wanting to convert a string array of numbers to a numerical array"
in which case SSCANF is much faster than STR2NUM.
"So the general rule seems to be"
use SSCANF if you can!
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!