Returning error messages if input criteria not met
Show older comments
I'm working on a function with input (i,j) that should only allow a 1x2 array as input, and also only allow i to be integers between 1 and 9, and j to be integers between 1 and 12. I am trying to make it to where my function stops and returns an error message if either of those conditions are not met.
Here is what I have:
function path = Survival(i,j)
if isrow(i,j)==0 || iscolumn(i,j)==1
error('Input must be 1x2 array')
end
if j>12 || j<1
error('j must be between 1-12')
end
if i>9 || i<1
error('i must be between 1-9')
end
If I only have one error and I run the script it works fine but I can't get it to work with all three. Thanks for any help.
Answers (2)
pt = [1,2] ; % change pt accordingly
m = pt(1) ;
n = pt(2) ;
% check dimensions
if ~(1<=m && m<=9) || ~(1<=n && n<=12)
error('check the input ')
end
Adam
on 6 Dec 2016
validateattributes( i, { 'double', 'single' }, { 'row', '>', 1, '<', 9 } )
validateattributes( j, { 'double', 'single' }, { 'row', '>', 1, '<', 12 } )
for example.
doc validateattributes
I use this all the time for my public functions. It is up to you what class of numbers you support. If your function supports all integer types too you can just use { 'numeric' } for the class.
This throws an error message for you. You can use extra arguments as shown in the documentation to add more to the error message, but I never bother since it is always obvious enough with the hyperlink to the line of the error.
Categories
Find more on Logical 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!