MATLAB recursive function [Factorials]

MATLAB recursive function [Factorials]

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

 

Where, fct(1) → 1


format compact
fct(5)

function a = fct(n)
    if n == 1
       a = 1;
    else
       a = n*fct(n-1);
       fprintf(%dn,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

MATLAB recursive function [Factorials]

Related posts

Leave a Reply

Your email address will not be published.