How to make error checking for each element in array?
6 views (last 30 days)
Show older comments
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 Comments
Answers (3)
Walter Roberson
on 30 Nov 2011
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 Comments
Walter Roberson
on 1 Dec 2011
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.
See Also
Categories
Find more on AI for Signals in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!