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

 Réponse acceptée

Adam Danz
Adam Danz le 19 Avr 2020
Modifié(e) : Adam Danz le 20 Avr 2020

1 vote

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 commentaires

Stephen23
Stephen23 le 19 Avr 2020
isnumeric(answerNum): when is the output of str2double not numeric?
Adam Danz
Adam Danz le 19 Avr 2020
Good point. That last condition is unnecessary. It is leftover from a different idea I initially had.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Identification dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by