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 compactfct(5)

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

Best Answer


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 compactfct(5)function a = fct(n)if n == 1a = 1;elsea = n*fct(n-1);fprintf("%d\n",a);endend

Cumulative/Recursive Results:

2624120ans =120

My Preferred Structuring:

format compactfct(5)function a = fct(n)if n > 1a = n*fct(n-1);elsea = n;endend