How to design a function that compute the factorial of an integer. The function outputs an error message if user enter a non negative value?

13 views (last 30 days)
function [ out ] = factorialeq( integer )
out=factorial(integer);
if( ~isreal(integer) || integer < 0)
error(message('MATLAB:factorial:NNegativeInt'))
end
This is what I have done but it doesnt work
  5 Comments
Guillaume
Guillaume on 11 Apr 2016
Well, actually, the order does not matter, the check is redundant anyway since it's already performed by factorial. You can take out the entire if statement, or move it before the call to factorial, it won't change the end result at all.

Sign in to comment.

Answers (2)

Alberto
Alberto on 11 Apr 2016
I'm not sure about what do you pretend, but I think that what you want to do is to check the input:
function [ out ] = factorialeq( integer )
if( ~isinteger(integer) || integer < 0)
error(message('MATLAB:factorial:NNegativeInt'))
out = [];
else
out=factorial(integer);
end
Please give more details.
Bests, Alberto.
  4 Comments
Alberto
Alberto on 11 Apr 2016
@Maria
But the function Factorial actually do that, don't?
  • factorial(-4)Error using factorial (line 20) N must be an array of real non-negative integers.
  • factorial(1.4)Error using factorial (line 20) N must be an array of real non-negative integers.
If you want an specific message you can put it into a try catch
function [ out ] = factorialeq( integer )
try
out=factorial(integer);
catch
disp('SPECIFIC MESSAGE')
out = 0;
end

Sign in to comment.


Image Analyst
Image Analyst on 11 Apr 2016
Try adapting this snippet:
% Ask user for one integer number.
defaultValue = 45;
titleBar = 'Enter an integer value';
userPrompt = 'Enter the integer';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
integerValue = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', integerValue);
uiwait(warndlg(message));
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!