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

1 ビュー (過去 30 日間)
David Pesetsky
David Pesetsky 2018 年 9 月 24 日
編集済み: Bish Erbas 2018 年 9 月 24 日
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 件のコメント
Walter Roberson
Walter Roberson 2018 年 9 月 24 日
s = 'two';
t = str2double(s);
if isnan(t); t = s; end

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2018 年 9 月 24 日
str2double() and test for nan, keep the original if you got nan.

Community Treasure Hunt

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

Start Hunting!

Translated by