How to make error checking for each element in array?
이전 댓글 표시
Hello guys, I am trying to get Matlab to check for errors for an input. The input can be entered in as an array and I would like for it to check each element if it is a negative value or non-numerical.
Here is what I have so far, it works if only a single number is entered but otherwise it crashes.
function [ volume ] = cube( a )
%p=imread('cubepict.png');
%imshow(p)
repeat = 1;
while repeat ==1
a = input ('Please enter a value or values for a according to the diagram: ', 's');
if any(~isnan(str2double(a)))
a = any(str2double(a));
end
if any(a < 0) |any(ischar(a))
disp ('Input(s) must be numerical and cannot contain negative values. Please try again.')
else repeat=0;
end
end
fid=fopen('cubelength.txt','w') ;
fprintf(fid, '%1.2i',a);
fclose(fid);
load cubelength.txt;
volume = a.^3;
fid2=fopen('volume.txt','w');
fprintf(fid2,'%1.2i',volume);
end
답변 (3개)
Walter Roberson
2011년 11월 30일
After you read "a" but before you do anything else to it:
a = regexp(a, ' ', 'split');
This will turn "a" in to a cell array of strings. This is needed because str2double() can only return one value per input string but is happy to do that for each cell array member.
Warning: your line
a = any(str2double(a));
is badly broken. It will set a to the scalar value 1 if at least one field in the input was a number, and will return 0 if the input was empty or if all of the fields in the input were non-numbers. Thus will thus turn the array of values in "a" in to a single (logical) value, which will not be useful for further processing.
댓글 수: 3
lbon jbn
2011년 11월 30일
Walter Roberson
2011년 12월 1일
What you need to know for that message is whether any of the conversions failed or resulted in a value less than 0.
You will find this logically easier to process if you do not keep overwriting a.
A_num = str2double(a);
if any(isnan(A_num)) || any(A_num < 0)
%complain, and then "continue" the loop
end
You will find that you can use this right after "a" has been split in to strings.
lbon jbn
2011년 12월 1일
카테고리
도움말 센터 및 File Exchange에서 AI for Signals에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!