how to take a number as input

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

isnumeric(answerNum): when is the output of str2double not numeric?
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

Asked:

on 19 Apr 2020

Edited:

on 20 Apr 2020

Community Treasure Hunt

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

Start Hunting!