CS10-8L: Computer Programming Laboratory
Machine Problem #7: Advanced Functions
OBJECTIVES
To understand, create, and implement subfunctions, anonymous functions, and functions with
variable number of input and output.
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. Subfunctions
1. It is possible to have more than one function in a given M-file. If one function calls another, the
first(calling) function would be the primary function, and the one that is called is a subfunction.
The name of the M-file would be the same as the name of the primary function to avoid confusion.
printrectarea.m
function printrectarea(len, wid)
% This function prints the rectangle area
% It calls a subfunction to calculate the area
area = calcrectarea(len,wid);
fprintf('For a rectangle with a length of %.2f\n',len)
fprintf('and a width of %.2f, the area is %.2f\n', wid, area);
function area = calcrectarea(len, wid)
% This function calculates the rectangle area
area = len * wid;
In Command Window, run:
>> printrectarea(4,6)
>> help printrectarea
>> help printrectarea>calcrectarea
B. Variable Scope
Prepared by: Geldof Resuello
Prepared date: March 2020
1. The scope of any variable is the workspace in which it is valid. The workspace created in the
Command Window is called the base workspace.
2. As we have seen before, if a variable is defined in any function it is a local variable to that function. To
demonstrate:
mysum.m
function runsum = mysum(vec)
% This function sums a vector
runsum = 0;
for i=1:length(vec)
runsum = runsum + vec(i);
end
In Command Window, run:
>> clear
>> who
>> disp(mysum[5 9 1])
>> who
Also, variables that are defined in the Command Window cannot be used in a function.
However, scripts (as opposed to functions) do interact with the variables that are defined in the Command
Window. For example:
mysummfile.m
% This script sums a vector
vec = 1:5;
runsum = 0;
for i = 1:length(vec)
runsum = runsum + vec(i);
end
disp(runsum)
In Command Window, run:
>> clear
>> who
>> mysummfile
>> who
3. Variables that are defined in the Command Window can be used in a script, but cannot be used in a
function. For example, the vector vec could be defined in the Command Window (instead of in the script).
However, this is a very poor programming style. It is better to pass the vector vec to a function.
Also, it is possible in Matlab to have global variables that can be shared by functions. Although there are
some cases in which using global variables is efficient, it is generally also a poor programming style.
4. When a function stops executing, the local variables from that function are cleared. With variables
declared as persistent variables, however, the value is not cleared so the next time the function is
called, the variable exists and retains its former value.
Prepared by: Geldof Resuello
Prepared date: March 2020
persistex.m
% This script demonstrates persistent variables
% The first function has a variable count
fprintf('This is what happens with a normal variable:\n')
func1
func1
% The second fn has a persistent variable count
fprintf('\nThis is what happens with a persistent variable:\n')
func2
func2
func1.m
function func1
% This function increments a variable count
count = 0;
count = count + 1;
fprintf('The value of count is %d\n',count)
func2.m
function func2
% This function increments a persistent variable count
persistent count
if isempty(count)
count = 0;
end
count = count + 1;
fprintf('The value of count is %d\n ',count)
In the Command Window, run:
>> persistex
>> func1
>> func2
C. Anonymous Functions
1. An anonymous function is a very simple, one-line function, which does not have to be stored in an M-
file. The syntax is:
fnhandle = @ (arguments) functionbody
The fnhandle stores the function handle, which is an essential way of referring to the function. For
example,
>> cirarea = @ (radius) pi * radius .^2;
>> cirarea(4)
>> cirarea(1:4)
>> prtran = @ () fprintf(‘%.2f\n’, rand);
>> prtran()
Prepared by: Geldof Resuello
Prepared date: March 2020
>> prtran
2. To save an anonymous function, it can be saved to a MAT-file, and then it can be loaded when needed
>> cirarea = @ (radius) pi * radius .^2;
>> save anonfns cirarea
>> clear
>> load anonfns
>> who
3. You can also create function handles for functions other than anonymous functions, both built-in and
user-defined functions.
>> facth = @factorial;
>> facth(5)
D. Function Functions
1. One reason for using function handles is to be able to pass functions to other functions. These are
called function functions.
fnfnexamp.m
function fnfnexamp(funh)
% Example of a function function. The handle of a function
% is passed and that function of x is plotted
x = 1:.25:6;
y = funh(x);
plot(x,y,'ko')
>> fnfnexamp(sin)
>> fnfnexamp(@sin)
>> fnfnexamp(@cos)
2. Another way of doing this is to use the built-in function str2func that will convert a string to a function
handle.
fnstrfn2.m
function fnstrfn2(funstr)
% A function name is passed as an argument to this
% function; it converts this to a function handle and
% then plots the function of x
x = 1:.25:6;
funh = str2func(funstr);
y = funh(x);
plot(x,y,'bo')
>> fnfnexamp('sin')
E. Variable Numbers of Arguments
Prepared by: Geldof Resuello
Prepared date: March 2020
1. It is possible to have a variable number of arguments, both input and output. A built-in cell array
varargin can be used to store a variable number of input arguments and a built-in cell array varargout
can be used to store a variable number of output arguments.
The function nargin returns the number of input arguments passed and the function nargout determines
how many output arguments are expected to be returned from a function.
2. Example of a variable number of input arguments:
areafori.m
function area = areafori(varargin)
% Calculates and returns the area of a circle in feet
% The radius is passed, and potentially the unit of
% inches is also passed, in which case the result will be
% given in inches instead of feet
n = nargin; % number of input arguments
radius = varargin{1}; % Given in feet by default
if n == 2
unit = varargin{2};
% if inches is specified, convert the radius
if unit == 'i'
radius = radius * 12;
end
end
area = pi * radius ^ 2;
>> areafori(3)
>> areafori(1, 'i ')
areafori2.m
function area = areafori2(radius, varargin)
% Calculates and returns the area of a circle in feet
% The radius is passed, and potentially the unit of
% inches is also passed, in which case the result will be
% given in inches instead of feet
n = nargin; % number of input arguments
if n == 2
unit = varargin{1};
% if inches is specified, convert the radius
if unit == 'i'
radius = radius * 12;
end
end
area = pi * radius ^ 2;
>> areafori2(3)
>> areafori(1, 'i ')
3. Example of a variable number of output arguments:
Prepared by: Geldof Resuello
Prepared date: March 2020
typesize.m
function [arrtype, varargout] = typesize(inputval)
% Demonstrates a variable number of output arguments
[r c ] = size(inputval);
if r==1 && c==1
arrtype = 's';
elseif r==1 || c==1
arrtype = 'v';
varargout{1} = length(inputval);
else
arrtype = 'm';
varargout{1} = r;
varargout{2} = c;
end
>> typesize(5)
>> [arrtype, len] = typesize(4:6)
>> [arrtype, r, c] = typesize([4:6; 3:5])
>> [arrtype, r, c] = typesize(4:6)
mysize.m
function [row col varargout] = mysize(mat)
% Demonstrates the use of nargout
[row col] = size(mat);
if nargout == 3
varargout{1} = row*col;
end
>> [r c] = mysize(eye(3))
>> [r c elem] = mysize(eye(3))
Prepared by: Geldof Resuello
Prepared date: March 2020
MACHINE PROBLEM
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 MP07_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.) posnum.m
Write a function posnum that prompts the user to enter a positive number and loops to error-check. It
returns the square root of the positive number entered by the user. It calls a subfunction in the loop to
print an error message. The subfunction has a persistent variable to count the number of times an error
has occurred.
Here is an example of calling the function:
>> squarerootvalue = posnum
Enter a positive number: -5
Error #1: Follow instructions!
Does -5.00 look like a positive number to you?
Enter a positive number: -33
Error #2: Follow instructions!
Does -33.00 look like a positive number to you?
Enter a positive number: 4
squarerootvalue = 2
Call the function and use values -5, -3, -1, 0, 9
2.) rectangular.m
Write a function rectangular that will receive a variable number of input arguments: the length and
width of a rectangle, and possibly also the height of a box that has this rectangle as its base. The
function should return the rectangle area if just the length and width are passed, or also the volume if
the height is also passed.
Here is an example of calling the function:
>> a = rectangular(2,3)
a=6
>> [a v] = rectangular(2,3,4)
a=6
v = 24
Run the function using l = 3, w =4 and l = 3, w = 4, h = 5
Prepared by: Geldof Resuello
Prepared date: March 2020
3.) stirling
An approximation for a factorial can be found using the Stirling’s formula:
n
n
n ! ≈ √ 2 πn ()
e
Write an anonymous function stirling to implement this.
Run the function using n = 10 and n = 1:2:10
Prepared by: Geldof Resuello
Prepared date: March 2020
IT131-8L Machine Problem Answer Sheet
Machine
7 (Advanced Functions) Score
Problem #
Name Section
1. Command Window Results:
posnum.m
Script:
2. Command Window Results:
rectangular.m
Script:
3. Command Window Results:
stirling definition
Prepared by: Geldof Resuello
Prepared date: March 2020