简体   繁体   中英

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

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.

递归过程


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM