Professional Documents
Culture Documents
What is Recursion?
Recursive problems are problems that are
essentially solved by solving lots and lots of smaller
instances of the same problem. We do this by
recalling our function INSIDE our function. Sounds
weird, but recursion is one way to represent data
break it down into the simplest case, or the case that will
signify you have reached your goal output. This is your
Terminating condition. An example of such is if you
were trying to use recursion to sum up all of the numbers is
a vector, you may go about this by adding it up one element
at a time, and then deleting the element you have just
added to the overall sum, or output. How would we
determine our base case here?
if isempty(vec) ! why? because when our vector is empty,
we have removed all that terms that have been added to the
overall sum, or our output.
Look at it:
vector = [3, 5, 1, 8, 7];
out = mySum(vector);
3 + 5 + 1 + mySum([8 7])
3 + 5 + 1 + 8 + mySum( 7 )
3 + 5 + 1 + 8 + 7 + mySum()
3 + 5 + 1 + 8 + 7 + ?????? what happens when our vector is empty? whats the
value of out? We set it to zero right? so we get:
3 + 5 + 1 + 8 + 7 + 0 and we didnt call another clone, so it has to stop here
correct? Yep. And the final value of out is: 3 + 5 + 1 + 8 + 7 + 0 = 24
Solution:
function ret =