Creating a MATLAB Function for Recursive Factorial Calculation

Learn how to create a recursive MATLAB function to calculate factorials with input validation and clear explanations for non-negative integers.

Brief Introduction

Creating a MATLAB Function for Recursive Factorial Calculation (matlab)
DESCRIPTION:
This example shows how to implement a recursive function in MATLAB to calculate the factorial of a non-negative integer. The function includes input checks to ensure the argument is valid and uses recursion to compute the result.

ADDITIONAL NOTES:
The function is designed for non-negative integers. For very large values, the result may exceed MATLAB's numeric capacity and cause overflow. Recursion is an elegant technique but not always the most efficient for very large factorial calculations.

EXPLANATIONS:
- The function first checks that the input is a non-negative integer, otherwise it throws an error.
- The base case of the recursion is when n is 0 or 1, where the factorial is 1.
- For values greater than 1, the function calls itself with n-1 and multiplies the result by n.
- This process continues until the base case is reached, then the call chain unwinds multiplying the values.

Example Code: matlab

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
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

Complete Example

% 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();

What do you need?

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.

Similar Topics