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)
Show older comments
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
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.
Answers (2)
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
Walter Roberson
on 11 Apr 2016
isinteger tests for integer datatype like uint8.
Hint: when does floor not change a value?
Alberto
on 11 Apr 2016
@Maria
- 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
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
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!