How can I classify a variable if it is a string or a number?

조회 수: 4 (최근 30일)
Toni
Toni 2014년 5월 13일
댓글: Benjamin Avants 2014년 5월 13일
I want to display if the costumer has introduced a number or a string when is requested.

채택된 답변

Benjamin Avants
Benjamin Avants 2014년 5월 13일
Use the class() function.
str = 'Test';
num = 1;
strcmp(class(str),'char')
true
strcmp(class(num),'double')
true
Of course, if the entry was prompted with inputdlg, all responses will be returned as strings. In that case, you'll need to try and convert the string to a number and examine the result. If str2num or str2double can't convert a string, they return NaN.
  댓글 수: 2
Walter Roberson
Walter Roberson 2014년 5월 13일
str2num() would convert 'pi' to a number...
Benjamin Avants
Benjamin Avants 2014년 5월 13일
True... so you may want to check for specific cases like that if they are likely to happen. Thankfully, there aren't that many.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by