Uploaded by Gift Stephens Mwale

6. CS211 FUNCTIONS

advertisement
THE COPPERBELT UNIVERSITY
SCHOOL OF ENGINEERING
APPLIED COMPUTING: CS211
@2022
Page 1 of 17
4.1 Introduction to MATLAB functions
A simple function in mathematics, f(x), associates a unique number to each value of x. The function can
be expressed in the form y=f(x), where f(x) is usually a mathematical expression in terms of x. A value of
y (output) is obtained when a value of x (input) is substituted in the expression.
Fig 4.1: Illustration of a functions capability to transform inputs to outputs
As you may recall, MATLAB provides a number of built-in functions such as sin(), cos(), exp(), sqrt() and
pow2(), among others. Some problems may not be amenable to MATLAB built-in functions and as such it
may be necessary to develop new functions. Generally, functions – whether user defined or predefinedpresent remarkable advantages in software development. The following are some of the advantages
afforded by the use of functions:
1. Independent testing of sub-tasks. Each sub-task can be written as an independent unit. The sub
task can be tested separately to ensure that it performs properly by itself before combining it into
the larger program. This step is known as unit testing. It eliminates a major source of problems
before the final program is even built.
2. Reusable code. In many cases, the same basic sub-task is needed in many parts of a program. For
example, it may be necessary to sort a list of values into ascending order many times within a
program, or even within other programs. It is possible to design, code, test, and debug a single
function to do the sorting and then to reuse that function whenever sorting is required. This
reusable code has two major advantages: it reduces the total programming effort required, and
it simplifies debugging, since the sorting function needs to be debugged only once.
3. Isolation from unintended side effects. Functions receive input data from the program that
invokes them through a list of variables called an input argument list, and return results to the
program through an output argument list. Each function has its own workspace with its own
variables, independent of all other functions and of the calling program. The only variables in the
calling program that can be seen by the function are those in the input argument list, and the only
Page 2 of 17
variables in the function that can be seen by the calling program are those in the output argument
list. This is very important, since accidental programming mistakes within a function can affect
only the variables within function in which the mistake occurred.
A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input
data through an input argument list, and returns results to the caller through an output argument list. The
general form of a MATLAB function is
The function statement marks the beginning of the function. It specifies the name of the function and the
input and output argument lists. The input argument list appears in parentheses after the function name,
and the output argument list appears in brackets to the left of the equal sign.
Example 1: Demonstration of functions
Use functional abstraction to develop a program that calculates the area of a circle.
Analysis
Problem statement: Develop a program that uses functional abstraction (encapsulation) to compute area
of a circle.
Input: radius
Output: area of a circle
Page 3 of 17
Design
Page 4 of 17
Implementation
Test
Case 1:
Radius=1 metre
Case 2:
Radius=2 metres
Maintenance
Consider providing function with feature to select various shape types and compute their areas.
NB: Type “help circle_area” at command prompt.
Page 5 of 17
4.2 Passing variables to MATLAB functions: The pass-by-value scheme
MATLAB programs communicate with their functions using a pass-by-value scheme. When a function call
occurs, MATLAB makes a copy of the actual arguments and passes them to the function. This copying is
very significant, because it means that even if the function modifies the input arguments, it won’t affect
the original data in the caller. This feature helps to prevent unintended side effects in which an error in
the function might unintentionally modify variables in the calling program. The following example
illustrates this concept.
Pogrammes circle_area and sphere_volume both use variable radius. The example illustrates that
although the first programme raises radius to the power two, the variable radius outside the function
remains unchanged and can be used by another programme, in this case sphere_volume.
Example 2: Develop a function to calculate the area of a circle given radius as input.
Page 6 of 17
Example 4: Develop a function to compute the volume of a sphere given radius as input.
Page 7 of 17
Example 5: Develop a program that computes the area and perimeter of a rectangle. It should take in the
length and width as input arguments and have two output arguments for area and perimeter.
Page 8 of 17
4.3 Optional arguments
Many MATLAB functions support optional input arguments and output arguments. For example, we
have seen calls to the plot function with as few as two or as many as seven input arguments. The
following is an illustration of the idea of Optional arguments using the plot function.
Example 6: Demonstrate the concept of optional arguments using the MATLAB plot function.
As shown in the foregoing example, a user has the option of using two or more arguments. This is possible
because the plot function has been designed to take the idea of optional arguments into account. We can
also do the same. Example 6 demonstrate how we can give user defined functions the capacity to account
for optional input and output arguments. Before we go to the example, let us look at key MATLAB builtin functions that will facilitate the addition of the Optional argument facility to our functions.
a. nargin—This function returns the number of actual input arguments that were used to call the
function. That is, how many arguments did you pass to the function when you called it? For
example, plot(x,y1) has a function call with two arguments whereas plot(x,y1,’r—‘,x,y2,’bo’) has
six input arguments. The function nargin counts the number of arguments that have been
provided at function call. Are they the right number? Is the question we ask when nargin is added
to our user-defined function.
b. nargout—This function returns the
number
of actual output
arguments
that were used to call the function.
c. nargchk—This function returns a standard error message if a function is called with too few or
too many arguments. Nargchk, checks the number of inputs a function is called with. It produces
output that can be passed to an error function which can produce an error message.
Page 9 of 17
min_args is the minimum number of input arguments the programme should be fed to run
whereas max_args specifies the maximum number of inputs a function can take. num_args is the
actual number of arguments the programme has been fed at the time of calling.
d. error—Display error message and abort the function producing the error. This function is used if
the argument errors are fatal. That is, if there is an error the entire program is brought to a halt
and an error message printed out. This is an important function built-in in MATLAB.
e. warning—Display warning message and continue function execution. This function is used if the
argument errors are not fatal and execution can continue. The warning function allows us to give
our programme the facility to indicate that something could be wrong with our inputs even
though it can be overlooked and the programme allowed to run based on the ‘limited’ inputs.
Example 7: Develop a function that accounts for Optional arguments when converting cartesian
coordinates to polar coordinates.
Page 10 of 17
Page 11 of 17
4.4 Sharing data between functions
In this section, we look at how values returned by one function can serve as input to another function.
This section illustrates of the key benefits of functional encapsulation, that is, it facilitates relatively easy
reusability of programmes.
Example 9:
Develop a programme made of three functions, whereby one function is used to obtain data supplied by
a user from the keyboard; the second function preprocesses the data to ensure every element is positive
and the third function generates a time series plot of the data.
getData()
Page 12 of 17
preprocessData()
Page 13 of 17
plotData()
Page 14 of 17
4.5 Nested functions
Functions can also be nested in a similar way decision and loop constructs were nested in earlier topics.
Why nest functions? Watch the accompanying video lecture. The following is a general structure of two
nested functions.
Example 9: Develop a programme of nested functions whereby the main function takes inputs of initial
velocity and final velocity and outputs change in kinetic energy. The inner function has mass as an internal
variable and can compute changes in momentum.
Page 15 of 17
4.6 Anonymous functions and function handles
All functions we have worked with thus far had to be stored in the workspace each time we initialized.
Anonymous functions can considerably simplify programmes especially where certain mathematical
functions are used numerous times. An anonymous function once initialized, will be held in the workspace
as an operator. When called to act upon data, the results will not be stored in the function’s variable
name. The anonymous function will act on the data without itself being altered in the workspace.
The general structure of an anonymous function is:
Functionhandlelever=@(arguments)(functionbody)
Example 10: Develop a program that uses an anonymous function to calculate the momentum of a fighter
jet given its velocity at particular instant.
Example 11: Develop a program that uses an anonymous function to compute the total resistance of
parallel circuit with four resistors.
==================================END=========================================
Page 16 of 17
NOTE:
Test two will cover the following topics:
(About 30% of test)
1. Term one work
----------------------------------------- ------------------------------------------------------------------------------------------(About 70% of test)
2. Decision constructs
3. Iterations
4. Functions
Ensure you study and practice. Watch the videos. Read the books recommended.
Page 17 of 17
Download