# Recursion or self-calling routine

### 1.- Basics

Recursion is a kind of tricky and smart construction which allows a function to call itself. The Matlab programming language supports it, so a function can call itself during its own execution. Recursive algorithms can be directly implemented in Matlab.

Here is a simple example of recursion, let's elaborate...

Example of recursive code:

function y = ten_exp(n)
% 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
y = 1

else
n %<< this line is not needed but for inspection
y = 10 * ten_exp(n-1)
end

Semicolons were avoided in those statements (on purpose) to see the value updates in different levels of the recursion. You can explore the code by running the step-by-step feature while at the editor.

This code has a construction using a branch. The comparison n == 0 is the base of the recursion, because it defines the final step or lowest level. This is the only way to get the program to stop calling itself.

The ‘else’ part 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 until it gets down to n = 0.

There are several considerations while using this self-calling technique:

• The first is that it is possible for the function to call itself forever and never return an answer. That happens in the code above if we enter a negative argument.
• The 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 line of code (10^n).
• The third consideration is that it needs more memory allocation. In calculations on large systems, memory space should not be wasted 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 compute a factorial number, but it is conceptually a recursive calculation easy to test and implement...

function y = fact(n)
% We have the highest number
y = n

% We go down to 0
if n == 0
y = 1

else
% We multiply by all the integers before ours,
% one at a time...
y = y * fact(n-1)
end

Again, these are the considerations for this example:

• It is possible for the function to call itself forever and never return an answer. That happens in the code above if we enter a negative argument.
• There are redundant calculations which can be time consuming. The code above uses instructions again and again that could be performed using a single built-in function (factorial(n)).

### 3.- Video: Puzzle solved with Recursivity

From 'Recursion' to home

From 'Recursion' to Matlab Examples
 Top

## Related pages

converting octal to decimalmatlab if multiple conditionsmatlab guiskvl and kcl problems with solutionshow to draw 3d graphsdecimal to binary conversion algorithmmatlab algebrasolving a matrix in matlabgauss jordan techniqueformula for charging a capacitorunit step matlabgenerate ascii tableascii to binary chartmatlab sqrtsecond degree polynomial regressionalgebra axiomspythagoras triangle calculatoriteration matlabhow to graph a piece wise functiontower of hanoi game solutionline in slope intercept form calculatorhow to learn matlab programmingintersection point of two vectorsmatlab gui for image processingascii to integerbell curve normal distributionheaviside step functionstaylor series for cosineconvert cartesian coordinates to polarfuture annuity calculatormotorcycle resale value calculatoralgorithm to convert decimal to binaryconvert decimal to octalexponential fitting in matlabdecimal to binmatlab sample codehalf life decay calculatorsolving equations with matlabconvert from cartesian to polarfactorial program using functiononline graphing calculator piecewise functionspascals triangle programascii code binary tablehow to define step function in matlabcalc integralpiecewise defined functionsconvert decimal to binary codelog log plot matlabprime factor calcmatlab scalar producthow do you calculate square feet from inchesfibonacci calculation formulaamortize mortgagevertical line matlabsolve two equations two unknowns matlableast squares polynomial fithow to learn matlab step by stephow to plot a 3d graph in matlabascii table for alphabetssolving equations matlabconvert ascii to charmaclaurin series for cos xhow to do lu factorizationmatlab definite integralfactors of49charging and discharging a capacitor in an r-c circuitcollatz sequenceplot 3d matrix matlabconverting cartesian to polarpascal triangle calculatoreuclidean algorithm gcdascii code for letter awinspice