Professional Documents
Culture Documents
OBJECTIVES
To understand, create, and implement nested functions in Matlab
To introduce recursive functions with some examples in Matlab
GRADING SYSTEM
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
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)
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)
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
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
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.
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.
Machine
8 (Nested & Recursive Functions) Score
Problem #
Name Section
1.
Command Window Results:
getreal.m
Script:
2.
Command Window Results:
combi.m
Script: