Error checking - Identifying non-numerical inputs

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

回答 (1 件)

Walter Roberson
Walter Roberson 2011 年 11 月 25 日

0 投票

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 件のコメント

lbon jbn
lbon jbn 2011 年 11 月 25 日
ok it works for the scalar, but something should be changed for the vector. str2double would not work for it, i tried str2mat too and that didn't work either. Sorry if I'm making noob mistakes I'm relatively new to matlab and programming in general.
lbon jbn
lbon jbn 2011 年 11 月 25 日
actually I thought it was working but not really...if you actually do type in a number I think when it the str2double converts it to something crazy and the answers you get for the volume do not make any sense.
Walter Roberson
Walter Roberson 2011 年 11 月 25 日
You need to define the syntax or syntaxes that the users may use to enter vectors. Space separated? Comma separated? As it is a range, what if the use uses "-" between two numbers? Can the user use [] around the numbers? Can the user use () around the numbers? What if the user enters more than two numbers for the range? What if they only enter one number?
Can the user enter numbers in exponent form? Can they use upper-case E for the exponent as well as lower case E? Can they use the Fortran-style D for the exponent? Is 1e-9 a valid input form? Is .1e-9 a valid input form? Is .e-9 a valid input form?
When you do input validation, you need to be very specific about what is permitted and what is not. Once you know what input formats you will accept, you also implicitly know how to find the boundaries of a number in the string, break it out of the rest of the string, and parse it in to a numeric value.
You can test str2double() from the command line. For example,
>> str2double('.1e-9')
ans =
1e-10
lbon jbn
lbon jbn 2011 年 11 月 25 日
For the scalar, I only want a number, exponential form to me doesn't really matter. For vector, I just want them to input [1 2 3 etc] I don't want 3-5 or anything like. I'm also not sure what the proper command would be to check for a vector? Would it be isvector?
But another concern is that for some reason I get crazy answers when I include the str2double command. Is there something I'm missing?
Walter Roberson
Walter Roberson 2011 年 11 月 25 日
Put a breakpoint in at the place you are using str2double(). Examine the string that is being converted; examine the converted value. If the two match, then you have a problem in your volume calculation code that you could debug by setting the value of that variable to the numeric value and stepping through the code. If the two do not match then show us the string and show us the str2double() that you get.
Do you want the users to input the '[' and ']' as part of their vector response? If so then your prompt should say that.
r = regexprep(r, '^\s+','');
r = regexprep(r, '\s+$','');
t = regexp(r, '^\s*\[(\d+\s*)+\]\s*$', 'tokens');
if isempty(t); error('wrong input format for vector'); end
tn = regexp(t{1}, '\s+', 'split');
r = cellfun(@str2double, tn);
lbon jbn
lbon jbn 2011 年 11 月 26 日
Hmm...I keep getting NaN when I check what it says for the str2double. It's really strange. I may just exclude error checking in these regards, matlab gives an error anyway lol. I'm going to talk with my professor and see how far he wants us to go. If I need to do more I'll probably be back, but if not, then I really appreciate your help man. You saved me hours and hours of frustration! Thanks!
Walter Roberson
Walter Roberson 2011 年 11 月 26 日
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.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

質問済み:

2011 年 11 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by