Is there a function like string2double that can handle a numerical input?

조회 수: 21 (최근 30일)
Hi!
I am importing data that sometimes imports as a string, and sometimes as a number. In all cases I want a number. Is there a function like string2double that can handle a numerical input?
Right now it works like:
>> str2num('2')
ans =
2
>> str2num(2)
Error using str2num (line 35)
Input must be a character vector or string scalar.
Ideally it would work like:
>> FunctionLikestr2num('2')
ans =
2
>> FunctionLikestr2num(2)
ans =
2
Thank you!

채택된 답변

Steven Lord
Steven Lord 2019년 1월 21일
First test if the input isnumeric. If it's not, try converting it from text data to a number.
  댓글 수: 2
Stephen23
Stephen23 2019년 1월 22일
편집: Stephen23 2019년 1월 22일
+1 a much more efficient solution.
The multiple type conversions used in the accepted answer are not necessary, and likely lose data precision and slow down the code. This is a much better answer: it makes it clear what the intent is.
Connor Brackley
Connor Brackley 2019년 1월 24일
In the end I used the answer Luna submitted, but I'll flag this as the accepted answer as the loss of data is a concern.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Luna
Luna 2019년 1월 21일
You can do it first convert to string then convert to numeric:
str2num(string(2))
str2num(string('2'))
Both gives you numeric 2.
  댓글 수: 5
Stephen23
Stephen23 2019년 1월 22일
편집: Stephen23 2019년 1월 22일
@Luna: unfortunately str2num hides an eval call inside itself, which is why experienced MATLAB users try to avoid using it (especially inside loops). That is why str2double is recommended. The documentation states: "str2double Similar to str2num, but offers better performance and works with string arrays and cell arrays of character vectors."
Luna
Luna 2019년 1월 22일
I didn't know that, thank you @Stephen Cobeldick. I noted that.
I will use recommended str2double then.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by