Error checking - Identifying non-numerical inputs
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello, I am having some difficulty with a program I'm trying to write (it's a volume calculator). When the user is asked to input a value for, say the radius of a sphere, I would like to give an error message if the value is a non-numerical value(ex. hello, &%%, etc..). There is also an option to enter a range of values and I wanted to make sure there is also an error message if someone does not enter an array for the input.
Here is what I have so far, this is just for one of the functions that calculates sphere volume:
function [ volume ] = sphere( r )
p=imread('sphere.png');
imshow(p)
type = input('Please specify if your input will be a scalar or vector (1 for scalar, 2 for vector): ');
if type == 1
r = input ('Please enter the radius: ');
if isscalar(r)==0
disp('Input must be a scalar. Please try again.')
else
if r < 0
disp ('r cannot be a negative value. Please try again.')
else volume = (4/3)*pi.*r.^3 ;
end
end
elseif type == 2
r = input ('Please enter a range of values for the radius: ');
if ismatrix(r)==0
disp('Input must be a vector. Please try again.')
else
if any(r < 0)
disp ('r cannot contain negative values. Please try again.')
else
fid=fopen('radii.txt','w') ;
fprintf(fid, '%1.2i',r);
fclose(fid);
load radii.txt;
volume = (4/3)*pi.*r.^3;
end
end
else
disp('ERROR. Response is invalid.')
end
end
0 Commenti
Risposte (1)
Walter Roberson
il 25 Nov 2011
input() in the form you show, always evaluates what the user types as a MATLAB expression, and returns the value of the expression to the program. Therefore if the user types, say, pi/2 then MATLAB will return 1.7<etc> to the program, not the string 'pi/2'.
In order to get the text of what the user typed for error checking purposes, you need to add the 's' option to input:
r = input('Please specify if your input will be a scalar or vector (1 for scalar, 2 for vector): ', 's');
Then, whatever the user types will be returned as a string, which you can then validate, and then use str2double() to convert to numeric form.
7 Commenti
Walter Roberson
il 26 Nov 2011
NaN returned from str2double() means that str2double() was not able to parse the string as a number. That is a definite problem, and usually means that your code has not properly split the numbers out of their containing string.
Again, set a breakpoint and examine the string carefully and test the conversion of the string from the command line; if you can come up with a sample string that you expect str2double to handle but which it returns NaN for, please post it here.
Vedere anche
Categorie
Scopri di più su Characters and Strings 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!