Input is a valid integer
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
How to check if the value entered by the user is a valid integer and not a negative number(such as -1,-9,-10 etc) or characters/strings(such as a, i,thank you)or special symbols(such as @,* etc) and also that is not equal to 0?
0 Commenti
Risposte (2)
Walter Roberson
il 29 Ott 2015
https://www.mathworks.com/matlabcentral/newsreader/view_thread/163080
DGM
il 31 Mag 2024
Modificato: DGM
il 31 Mag 2024
Assuming the input x is a char vector from input() which represents a numeric scalar:
isvalidnumber('56') % positive scalar integer is okay
isvalidnumber('-56') % not valid (not positive)
isvalidnumber('56.2') % not valid (noninteger)
isvalidnumber('[56 23]') % not valid (nonscalar)
isvalidnumber('asdf') % not valid (non-numeric)
isvalidnumber('56E3') % E-notation is valid (56000 is a positive scalar integer)
function isvalid = isvalidnumber(x)
x = str2double(x); % NaN if text or nonscalar numeric
isvalid = (x > 0) & (mod(x,1) == 0); % true only for positive integers
end
There are probably other ways to approach this, but it's a basic start. If you really want to improve things, take a step back and stop designing around accumulating parameters interactively via input().
0 Commenti
Vedere anche
Categorie
Scopri di più su Argument Definitions in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!