clearer explanation of function level scope for re

2019-08-05 06:04发布

问题:

This is an example from the book 'Matlab for Neuroscientists'. I don't understand the order in which, or why, g gets assigned a new value after each recursion. Nor do I understand why "factorial2" is included in the final line of code.

here is a link to the text

Basically, I am asking for someone to re-word the authors explanation (circled in red) of how the function works, as if they were explaining the concept and processes to a 5-year old. I'm brand new to programming. I thought I understood how this worked from reading another book, but now this authors explanation is causing nothing but confusion. Many thanks to anyone who can help!!

回答1:

A recursive method works by breaking a larger problem into smaller problems each time the method is called. This allows you to break what would be a difficult problem; a factorial summation, into a series of smaller problems.

Each recursive function has 2 parts:
1) The base case: The lowest value that we care about evaluating. Usually this goes to zero or one.

if (num == 1)
  out = 1;
end


2) The general case: The general case is what we are going to call until we reach the base case. We call the function again, but this time with 1 less than the previous function started with. This allows us to work our way towards the base case.

out = num + factorial(num-1);

This statement means that we are going to firstly call the function with 1 less than what this function with; we started with three, the next call starts with two, the call after that starts with 1 (Which triggers our base case!)

Once our base case is reached, the methods "recurse-out". This means they bounce backwards, back into the function that called it, bringing all the data from the functions below it!
It is at this point that our summation actually occurs.

Once the original function is reached, we have our final summation.

For example, let's say you want the summation of the first 3 integers. The first recursive call is passed the number 3.

  function [out] = factorial(num)
     %//Base case
     if (num == 1)
        out = 1;
     end
  %//General case
  out = num + factorial(num-1);

Walking through the function calls:

factorial(3); //Initial function call

//Becomes..
factorial(1) + factorial(2) + factorial(3) = returned value

This gives us a result of 6!