how to take a number as input
7 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
Adam Danz
on 19 Apr 2020
Good point. That last condition is unnecessary. It is leftover from a different idea I initially had.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!