Error checking - Identifying non-numerical inputs
조회 수: 5 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Walter Roberson
2011년 11월 25일
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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!