or self-calling routine
2.- Example with Factorials
3.- Video: Solve a Puzzle with Recursivity
is a kind
of tricky and smart construction which
allows a function to call itself. The Matlab programming language
so a function can call
itself during its own execution. Recursive
algorithms can be directly implemented in Matlab.
Here is a simple
recursion, let's elaborate...
Example of recursive code:
function y =
This is a recursive program for computing y = 10^n.
The program works only if n is a nonnegative integer.
If n is negative, the algorithm won't stop.
if n == 0
%<< this line is not
needed but for inspection
y = 10
Semicolons were avoided
in those statements (on purpose) to see
the value updates in different levels of the recursion. You can explore
code by running the
step-by-step feature while at the editor.
code has a construction using a branch. The comparison
n == 0 is the base of the recursion, because it defines the final step
lowest level. This is the only way to get the program to stop calling
in the branch is the key to recursivity. The trick is
that it is calling a lower value (n - 1), and it will continue to do so
it gets down to n = 0.
There are several considerations while using this self-calling
first is that it is possible for the function
to call itself forever and never return an answer. That happens in the
above if we enter a negative argument.
second is that recursion can lead to
redundant calculations which can be time consuming. The code above uses
instructions again and again that could be performed using a single
third consideration is that it needs more memory
allocation. In calculations on large systems, memory space should not
on program overhead.
On the other hand, recursive
programs can be easier to write
and read than nonrecursive programs.
2.- Recursivity to solve Factorials
Now, we’re going to write
a function to compute a factorial
(n!) using this technique, again. We know that it’s not the most
efficient way to
factorial number, but it is conceptually a recursive calculation easy
function y =
We have the highest number
y = n
We go down to 0
if n == 0
% We multiply by all the
integers before ours,
% one at a time...
y = y * fact(n-1)
are the considerations for this example:
is possible for the function to call itself
forever and never return an answer. That happens in the code above if
a negative argument.
are redundant calculations which can be
time consuming. The code above uses instructions again and again that
performed using a single built-in function (factorial(n)).
3.- Video: Puzzle solved with Recursivity
'Recursion' to home
From 'Recursion' to Matlab