You are on page 1of 6

CS10-8L: Computer Programming Laboratory

Machine Problem #8: Nested and Recursive Functions

OBJECTIVES
 To understand, create, and implement nested functions in Matlab
 To introduce recursive functions with some examples in Matlab

GRADING SYSTEM

From (%) To (%) Grade

0.00 64.99 5.00


65.00 68.89 3.00
68.9 72.89 2.75
72.9 76.79 2.50
76.8 80.69 2.25
80.7 84.59 2.00
84.6 88.49 1.75
88.5 92.39 1.50
92.4 96.29 1.25
96.3 100.00 1.00

INSTRUCTIONS
A. Nested Functions
1. The terminology for nested functions is that an outer function can have within it inner functions.

nestedvolume.m
function outvol = nestedvolume(len, wid, ht)
% Demonstrates a nested function
outvol = base * ht;
function outbase = base
outbase = len * wid;
end % base function
end % nestedvolume function

In Command Window, run:


>> v = nestedvolume(3, 5, 7)

nestedvolume2.m
function outvol = nestedvolume2(len, wid, ht)
% Demonstrates scope within a nested function
disp('This function calculates a volume')
% Call the base function, and calculate and
% print the volume
outvol = base * ht;
fprintf(‘outvol is %.1f\n’, outvol)

Prepared by: Geldof Resuello


Prepared date: March 2020
fprintf(‘cvar is %.1f\n’, cvar)
% Call the printstuff function
printstuff
% Not valid because it is an output argument:
% fprintf(‘outbase is %.1f\n’, outbase)
function outbase = base
bvar = len * wid;
cvar = len * wid;
outbase = bvar;
end
function printstuff
fprintf(‘outvol is %.1f\n’, outvol)
%Not valid because bvar is not used in nestedvolume2:
% fprintf(‘bvar is %.1f\n’, bvar)
fprintf(‘cvar is %.1f\n’, cvar)
end
end

In Command Window, run:


>> v = nestedvolume2(3, 5, 7)

B. Recursive Functions
Recursion occurs when something is defined in terms of itself.

fact.m
function facn = fact(n)
% This function recursively finds n!
if n == 1
facn = 1;
else
facn = n * fact(n−1);
end

prtwords.m
function prtwords(sent)
% This function recusively prints the words in a string
% in reverse order
[word, rest] = strtok(sent);
if ~isempty(rest)
prtwords(rest);
end
disp(word)

In Command Window, run:


>> fact(5)
>> prtwords('what does this do')

C. Menu-Driven Modular Program

Prepared by: Geldof Resuello


Prepared date: March 2020
Many longer, more involved programs that have interaction with the user are menu-driven, which means
that the program prints a menu of choices and then continues to loop to print the menu of choices until the
user chooses to end the program.

A modular menu-driven program typically would have a function that presents the menu and gets the
user’s choice, as well as functions to implement the action for each choice. These functions may have
subfunctions. Also, the functions would error-check all user input.

As an example of such a menu-driven program, we will write a program to explore the constant e.

eapplication.m
% This script explores e and the exponential function
% Call a function to display a menu and get a choice
choice = eoption;
% Choice 4 is to exit the program
while choice ~= 4
switch choice
case 1
% Explain e
explaine;
case 2
% Approximate e using a limit
limite;
case 3
% Approximate exp(x) and compare to exp
x = input('Please enter a value for x: ');
expfn(x);
end
% Display menu again and get user’s choice
choice = eoption;
end

eoption.m
function choice = eoption
% Print the menu of options and error-check
% until the user pushes one of the buttons
choice = menu(‘Choose an e option’, ‘Explanation’, ...
‘Limit’, ‘Exponential function’, ‘Exit Program’);
% If the user closes the menu box rather than
% pushing one of the buttons, choice will be 0
while choice == 0
disp(‘Error - please choose one of the options.’)
choice = menu(‘Choose an e option’, ‘Explanation’, ...
‘Limit’, ‘Exponential function’, ‘Exit Program’);
end

explaine.m

Prepared by: Geldof Resuello


Prepared date: March 2020
function explaine
% This function explains a little bit about e
fprintf(‘The constant e is called the natural’)
fprintf(‘ exponential base.\n’)
fprintf(‘It is used extensively in mathematics and’)
fprintf(‘ engineering.\n’)
fprintf(‘The value of the constant e is ~ 2.1718\n’)
fprintf(‘Raising e to the power of x is so common that’)
fprintf(‘ this is called the exponential function.\n’)
fprintf(‘An approximation for e is found using a limit.\n’)
fprintf(‘An approximation for the exponential function’)
fprintf(‘ can be found using a series.\n’)

limite.m
function limite
% Approximates e using a limit
% Call a subfunction to prompt user for n
n = askforn;
fprintf(‘An approximation of e with n = %d is %.2f\n’, ...
n, (1 + 1/n) ^ n)
function outn = askforn
% This subfunction prompts the user for n
% It error-checks to make sure n is a positive integer
inputnum = input(‘Enter a positive integer for n: ’);
num2 = int32(inputnum);
while num2 = inputnum || num2 < 0
inputnum = input(‘Invalid! Enter a positive integer: ’);
num2 = int32(inputnum);
end
outn = inputnum;

expfn.m
function expfn(x)
% Compares the built-in function exp and a
% series approximation
fprintf(‘Value of built-in exp(x) is %.2f\n’,exp(x))
% n is arbitrary number of terms
n = 10;
fprintf(‘Approximate exp(x) is %.2f\n’, appex(x,n))
function outval = appex(x,n)
% Approximates e to the x power using terms up to x to the nth power
% Initialize the running sum to 1 (for the first term)
outval = 1;
runprod = 1;
for i = 1:n
runprod = runprod * i;
outval = outval + (x^i)/runprod;
end
MACHINE PROBLEM

Prepared by: Geldof Resuello


Prepared date: March 2020
Answer the following problems using commands in Matlab. Make sure to indicate the commands in your
submission, as specified in the Answer Sheet. Important: Only upload the Answer Sheet (i.e. exclude the
Instructions part). Save the file as MP08_Lastname.pdf Check the deadline indicated in Blackboard.
Failure to submit on time will incur an automatic grade of 0 while failure to follow instructions will incur
deductions.

Create the scripts for the following problems.

1.) getreal.m
The two real roots of a quadratic equation a x 2+ bx+ c=0 , where a ≠ 0 are given by
−b ± √ D
2∗a
where the discriminant D=b2−4 ac . Write a function getreal to calculate and return the roots of a
quadratic equation. Pass the values of a, b, c to the function. Use one nested function getinput to get
a correct input (remember: a should not be zero) and one nested function calcdisc to calculate the
discriminant.

Call your functions using the following:


>> getreal(1, 9, 20)
>> getreal(0, 1, 1)
>> getreal(2, 9, 5)

2.) combi.m
Combinatorial coefficients can be defined recursively as follows:
1 ,if m=0∨m=n
C ( n , m )=
{C ( n−1 ,m−1 )+C ( n−1 , m ) , otherwise
Write a recursive function combi to implement this definition.

Call your functions using the following:


>> combi(1, 0)
>> combi(2, 2)
>> combi(5, 4)

Prepared by: Geldof Resuello


Prepared date: March 2020
IT131-8L Machine Problem Answer Sheet

Machine
8 (Nested & Recursive Functions) Score
Problem #  
Name Section
 

1.
Command Window Results:

getreal.m
Script:

2.
Command Window Results:

combi.m
Script:

Prepared by: Geldof Resuello


Prepared date: March 2020

You might also like