How to make error checking for each element in array?
6 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(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 个评论
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 AI for Signals 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!