Function changing the display?
19 次查看(过去 30 天)
显示 更早的评论
if true
% code
function [ out ] = factorialeq( integer )
if( ~isinteger(integer) || integer < 0)
disp('error')
else
out=factorial(integer);
end
I want it to display and error message saying the input is non integer. Is that possible. Or since I'm using the isinteger the error message has already been set. Can I change it to display what I want it to say?
0 个评论
回答(2 个)
Guillaume
2016-4-11
It's still not very clear what you want to do since the built-in factorial function that you're calling will carry out the check and display the error message for you.
Anyway, you can pass any string you want to display to the error function:
error('The input must be a non-negative integer');
0 个评论
Steven Lord
2016-4-11
There are two main issues with the code you wrote. The first is that the isinteger function doesn't do what you think it does. It does not check that its input contains integer values but that its input is of an integer type.
isinteger(5) % returns false
isinteger(int8(5)) % returns true
The second issue is that in the case where the input is invalid, you don't assign a value to the variable being returned as output. This will cause MATLAB to throw an error, but it won't be the one you expect or want. I recommend doing as Guillaume suggests and using error instead of disp.
But as Guillaume also pointed out, the factorial function included with MATLAB already does error for noninteger values. So if you wanted to throw a different error message, I would probably just use try and catch. Call factorial inside the try and if you reach the catch throw your own error. I'm not going to post the code since I suspect this is part of a homework assignment, but it's only going to be a couple lines long.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!