Search code examples
functionmatlabrecursionfactorial

MATLAB recursive function [Factorials]


The code works but I am confused. When n==1, I am assigning a=1, shouldn't that overwrite the value and return only 1?

format compact
fct(5)

function a = fct(n)
    if n==1
       a = 1; 
    else 
       a = n*fct(n-1);
    end
end

Solution

  • This is how I picture it... Below is a recursion/factorial diagram that shows the cascading effect of the recursive calls. At the deepest recursive call fct(1) is evaluated which is equal to 1 given by the first if statement. Each recursive call is therefore defined by a deeper recursive call. I typically like to decompose the recursive function until reaching its terminating case. I guess a way to phrase it is "a function within function" not so much of a loop.

    Recursive Process


    Where, fct(1) → 1


    format compact
    fct(5)
    
    function a = fct(n)
        if n == 1
           a = 1;
        else
           a = n*fct(n-1);
           fprintf("%d\n",a);
        end
    
    end
    

    Cumulative/Recursive Results:

    2
    6
    24
    120
    
    ans =
       120
    

    My Preferred Structuring:

    format compact
    fct(5)
    
    function a = fct(n)
        if n > 1
           a = n*fct(n-1);
        else
           a = n;
        end
    end