how to take a number as input

7 views (last 30 days)
karan kantharia
karan kantharia on 19 Apr 2020
Edited: Adam Danz on 20 Apr 2020
I am, writing a code in which the user is aked to input a value. the value should be restricted to numbers only and no string. if the user enters anything other than a number error message should be displayed

Accepted Answer

Adam Danz
Adam Danz on 19 Apr 2020
Edited: Adam Danz on 20 Apr 2020
You can create an input dialog box using answer = inputdlg(prompt,dlgtitle) (see that page for additional input options). The output will be a cell array of characters (or an empty cell array).
Convert the output to numeric
answerNum = str2double(answer);
Use a conditional error enforcing numeric input
if isempty(answerNum) || isnan(answerNum) % || ~isnumeric(answerNum)
error('Input must be numeric.')
end
  2 Comments
Stephen23
Stephen23 on 19 Apr 2020
isnumeric(answerNum): when is the output of str2double not numeric?
Adam Danz
Adam Danz on 19 Apr 2020
Good point. That last condition is unnecessary. It is leftover from a different idea I initially had.

Sign in to comment.

More Answers (0)

Categories

Find more on App Building in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!