"

5 User-Defined Functions

All program examples that have been presented up to this point have been in the form of a “script”, which is a largely unstructured code sequence  in a single file. That is sufficient for short, simple programs. For larger, more complex programs, there are advantages to a modular approach, in which the code is divided into sub-programs, each of which performs a task that makes up a portion of the overall algorithm. In various programming languages, these units of code may be called subroutines, procedures, or methods. In MATLAB, they are called functions.

The benefits of a modular program design include:

  • easier debugging and maintenance
  • more compact and readable code
  • facilitation of teamwork

This chapter introduces the basics of writing a user-defined function in MATLAB. Chapter 8 explores the concept of program structure in more detail.

Lecture Video 5.1 – Introduction to User-Defined Functions

 

5.1 Relationship of a Function to a Main Program

It is common for a program to perform a given task numerous times. Rather than duplicate the code to perform that task, it can be incorporated into a function, which is called repeatedly. In fact, the scripts that we have presented previously contained many function calls. For example, in this script, every line is actually a function call:

x = linspace (-5, 5, 100);

y = 2.5*sin(4*pi*x);

figure()

plot (x,y)

xlabel('x values')

ylabel('y values')

title ('sine function')

linspace, sin, figure, plot, xlabel, ylabel, and title are all functions that are included in MATLAB. Some, like linspace, are actually written in ordinary MATLAB code, while others, like plot, are implemented in lower-level code. The latter type is called a built-in function. If there is no MATLAB function to perform a task, a user can write a user-defined function, which can be called from various programs just like any other function.

Most function calls, like those in the previous example, have certain elements in common. The general form of a function call is

outputs = function_name (inputs)

Consider the first line of the script:

x = linspace (-5, 5, 100);

The name of the function, linspace, appears just to the right of the equals sign; the output, x, appears to the left of the equal sign; the inputs, -5, 5, 100, are enclosed within parentheses after the function name. The meaning of those values depends on how the function is defined. In the case of a MATLAB built-in or library function, you must refer to the documentation to determine what value(s) to pass to the function and in what order, and what output(s) it returns. The first step in creating a user-defined function is to define its inputs and outputs.

Notice that not all functions return an output – for example, xlabel, ylabel, and title. There are some functions, like figure, that do not require an input.

5.2 Defining a Function

In this chapter, all user-defined functions will be external functions – that is, each function will be in a separate file, and the name of the file must match the name of the function. Chapter 8 shows other ways that functions can be organized.

To see the structure of a user-defined function, consider the standard MATLAB function, linspace, which is reproduced below. This function uses many MATLAB features that are covered in later chapters. The key points are highlighted in the comments on the pdf. The most important ones to take note of are:

  • The file name (linspace.m) must match the name of the function (linspace)
  • A function definition always begins with the word function. In an external function, there must be no code before this function definition line
  • The input values are passed to the function by the caller (main script) through its input arguments. Comparing the list of input arguments (d1, d2, n) with the input values (-5, 5, 100) in the function call in the example above, the values of these variables are d1 = -5, d2 = 5, and n = 100
  • At some point in the body of the function, the output argument (y) is assigned a value (or an array of values in this case). That determines what is returned by the function. Unlike other languages, no return statement is required.

 

There is one more point that is worth reiterating – the main reason for writing a function is so that this lengthy block of code does not have to be repeated every time it is used. Instead, only a single line is needed to call the function each time.

 

Checkpoint 6.1: Function Call

 

Lecture Videos 5.2-5.4 – Writing and Calling Functions

 

Checkpoint – user-defined function definition

 

Checkpoint – user-defined function call

 

Problems

  1. Calculating Coin-flip Probability
a) Write a function that calculates the probability of obtaining k heads in n flips of a possibly biased coin, where the probability of a head on any given flip is p. The equation is:
[latex]\\[/latex]
[latex]P(k\ heads\ in\ n\ flips) = \frac{n!}{k! (n-k)!}p^k\ (1-p)^{n-k}[/latex]
[latex]\\[/latex]
where ! is the factorial operation, for which you can use the MATLAB function, factorial. The function should take 3 input arguments: n, k, and p, and return 1 output argument, P.
b) Try your function with n=5, k = 3, and p = 0.5. The result should be 0.3125.
c) Try to construct a few more test cases for which you can easily evaluate whether the answer is correct, for example all heads or no heads.
[latex]\\[/latex]

   2. Simple String Parsing

Write a function that accepts a character array representing a person’s full name and returns the person’s last name.
For purposes of this exercise, the name can be assumed to be in this format:
    • Last, First (e.g., ‘Toney, James’)
A reasonable approach to this problem is as follows:
    • Find the position of the comma using the find() function.
    • Return the portion of the array from the first character to the one before the comma.

[latex]\\[/latex]

   3. A Plotting Function
Create a function that takes the following inputs:
    • A data matrix, where the first column contains the x-values, and each additional column contains the y-values for one data series
    • A string array containing the names to use for the axis labels
    • A string array containing the names to use for the legend
    • A string to use for the title
The function should do the following:
    • plot columns 2 through N (where N is the number of columns in the matrix) vs. column 1, all on the same graph. (There will be N-1 curves on the plot)
    • use the provided strings to add the axis labels, legend and title
    • scale the x and y axes so that they precisely span the range of values in the matrix (for the y-axis, the limits should go from the smallest value in any of the data series to the largest value in any of the data series – use the min and max functions with appropriate indexing).
A simple script to test your function with random data is as follows (assuming that you called the function “my_plot”):
d = [[1:100]', rand(100, 4)];  %generate 4 columns of random data
my_plot(d, ["x data", "y data"], ["y1", "y2", "y3", "y4"], "some random data")
The resulting plot should look something like this:

Find an error? Have a suggestion for improvement? Please submit this survey.

License

MATLAB Programming for Engineering Applications Copyright © by James Toney and jayakumar5. All Rights Reserved.