string that may or may not need to be converted to num...

I am bringing a string into a function. I need to convert it to num ONLY if it's intended as a number like 2, 40, 100... but when the user enters it as something else, leave it as a string. Can that be done?
Thanks!

 채택된 답변

Bish Erbas
Bish Erbas 2018년 9월 24일
편집: Bish Erbas 2018년 9월 24일
Yes. Take a look at the function below:
str2num
Edit: OP clarified their question and one way to accomplish what they need would be using the following function:
Edit2: Use str2double instead. See comments section for details.

댓글 수: 5

No... that doesn't leave the string alone if it's actually a string..
>> str2num('2')
ans =
2
>> str2num('two')
ans =
[]
Bish Erbas
Bish Erbas 2018년 9월 24일
편집: Bish Erbas 2018년 9월 24일
I see. That part wasn't clear in your question. Try this:
Note that str2double is preferred over str2num, because str2num is a wrapper around eval, with all of its inherent disadvantages.
@Stephen Cobeldick is absolutely right. Thanks for the helpful reminder. Old habits die hard. I gotta learn to remember using the more efficient str2double
s = 'two';
t = str2double(s);
if isnan(t); t = s; end

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2018년 9월 24일

1 개 추천

str2double() and test for nan, keep the original if you got nan.

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

질문:

2018년 9월 24일

편집:

2018년 9월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by