Function changing the display?

19 views (last 30 days)
Maria De Silva
Maria De Silva on 11 Apr 2016
Answered: Steven Lord on 11 Apr 2016
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?

Answers (2)

Guillaume
Guillaume on 11 Apr 2016
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');

Steven Lord
Steven Lord on 11 Apr 2016
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.

Categories

Find more on Data Type Identification 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!