Learn how to create a recursive MATLAB function to calculate factorials with input validation and clear explanations for non-negative integers.
function f = fattorialeRicorsivo(n)
% fattorialeRicorsivo Calculates the factorial of a non-negative integer using recursion
% f = fattorialeRicorsivo(n) returns the factorial of n.
% n must be a non-negative integer.
% Input check: must be a non-negative integer
if ~isscalar(n) || n < 0 || floor(n) ~= n
error('Input must be a non-negative integer.');
end
% Base case: factorial of 0 or 1 is 1
if n == 0 || n == 1
f = 1;
else
% Recursive step: n * factorial of (n-1)
f = n * fattorialeRicorsivo(n - 1);
end
end% Example script to test the recursive factorial function
function testFactorial()
% Recursive factorial function
function f = fattorialeRicorsivo(n)
% fattorialeRicorsivo Calculates the factorial of a non-negative integer using recursion
% f = fattorialeRicorsivo(n) returns the factorial of n.
% n must be a non-negative integer.
% Input check: must be a non-negative integer
if ~isscalar(n) || n < 0 || floor(n) ~= n
error('Input must be a non-negative integer.');
end
% Base case: factorial of 0 or 1 is 1
if n == 0 || n == 1
f = 1;
else
% Recursive step: n * factorial of (n-1)
f = n * fattorialeRicorsivo(n - 1);
end
end
% Test the function with some values
testValues = [0, 1, 5, 7];
for i = 1:length(testValues)
n = testValues(i);
fprintf('Factorial of %d is %d\n', n, fattorialeRicorsivo(n));
end
end
% Run the test
testFactorial();MATLAB: development environment to run and test the function.
MATLAB Function: .m file containing the recursive function 'fattorialeRicorsivo'.
Input: non-negative integer for which to calculate the factorial.
Output: integer value corresponding to the factorial of the given number.
Input check: verifies that the input is a non-negative integer.
No external dependencies or toolboxes required.