MATLAB Programming Part II: Functions

Grady Wright
Department of Mathematics
Boise State University

In this tutorial, we will study more advanced MATLAB programming. The main goal of this tutorial is to demonstrate how to write functions in MATLAB. In the previous tutorial, MATLAB Programming Part I, we learned how to write very simple programs that could, at best, request input from the user. When writing more sophisticated programs, it is necessary split the problem up into functions that can be passed input values and return the necessary output values. This is what we cover in this tutorial.

Note that, it is highly recommended that you implement the examples of this tutorial, run them, and carefully compare the output with the code.

Functions in MATLAB

You have already encountered functions that are built into MATLAB. For example, sin() is a function that takes an argument (in radians) and returns the sine of the value as output. As you start to write your own programs in MATLAB you will need to create your own functions that take one or more input arguments, operate on them, and return one or more results. For example, when you write your own non-linear root finder (e.g. Newton's method), you will most certainly need a loop that calls the non-linear function and it's derivative several times. It is certainly possible to write this function explicitly in your loop. However, that is not good programming practice since you would have to modify your general solver for every new specific function you want to input.

To introduce programming with functions in MATLAB, we will use the following example: Create a general program for graphing a given function over a given range.

Preliminaries

Before we begin, we must first look at the syntax for a function in MATLAB.

function y=<function_name>(argument list)

commands

end

This code should be written and saved in a separate m-file. The name of the file should coincide with the name of the function, i.e. <function_name>.m (remember you must save the file with a .m after the file name).

Example

We illustrate the syntax for the body of a MATLAB function by implementing the mathematical function

$$ f(x) = \sum_{k=0}^{50} \frac{(-1)^k}{2^{2k}(k!)^2}x^{2k}. $$ Additionally, we will vectorize this function so that it can operate correctly on vector-valued input. The function above represents the truncated Taylor series expansion for the $J_0$-Bessel function to 51 terms.

$J_0$ Bessel Function


% Filename: besselj0.m 

function y = besselj0(x)

N = 50;
y = 0*x;

for k = 0:N
    y = y + ((-1)^k/(2^(2*k)*factorial(k).^2))*x.^(2*k);
end

end

This code must be saved in your working directory as a separate m-file with the name besselj0.m. Note how we have not used the clear command. This is because all variables inside functions are local to that function (unless specified otherwise by using the GLOBAL command, which you should avoid).

Programming with Functions

Now, we illustrate how we can actually program with functions by solving the problem posed by the above example. We want a general MATLAB function that plots a given mathematical function over the domain [a,b]. This can be accomplished with the following MATLAB function.


% Filename: fplotter.m 

function fplotter(g,a,b)

x = linspace(a,b,501); % x-values over the range [a,b] at which to evaluate g

y = feval(g,x); % evaluate the function g at all the values in x

plot(x,y); % plot the function g

xlabel('x'); % label the x-axis

ylabel('f(x)'); % label the y-axis

end

This function must be saved as a separate m-file with the name fplotter.m. It must also be saved in the same directory as besselj0.m. Note that this is a very naive implementation of the function plotter. If we were going to make it more robust, we would want to put in code for checking the range of (a,b) and checking whether or not the function g exists. Also, it would be advantageous to base the number of points that are used to divide up the plot interval on the values of a and b.

To plot the function in besselj0.m using fplotter, first go to the MATLAB command window then change to the working directory that corresponds to the directory containing the two functions. Next, type the command

  >>fplotter(@besselj0,-3,3)

This will call the function fplotter with the function besselj0 and plot it over the range $[-3,3]$. Make sure you understand how this example works! It will help you with many of the homework problems.

Note that we can now use fplotter over and over again to plot other functions without changing the code.

Anonymous Functions

The above process of writing functions in MATLAB is the most general, and the most powerful. However, it can be a bit tedious when the function you want to create and use is very simple. For example, suppose you wanted to use the fplotter function above to plot $f(x) = \cos(\sin(x)-\pi)^2$. Instead of having to create a new m-file and store it on your harddrive, MATLAB offers a simple alternative with so called anonymous functions. Here is the notation for defining $f(x)$ as an anonymous function in the command window.
  >>f = @(x) cos(sin(x)-pi).^2; 
These anonymous functions can also be defined in scripts (and other functions). We can use the fplotter function to plot $f(x)$ over $[-\pi,\pi]$ as follows:
  >>fplotter(f,-3,3)
Note that in the case of an anonymous function it is not necessary to include the @ symbol in front of the function name.

Exercise 1.
Make a plot of the function $f(x) = e^{-x^2}\cos(3x)$ over the interval $[-\pi,\pi]$.

Exercise 2.
Rewrite your script from Exercise 2 of
MATLAB Programming I in the form of a function. As input, let the user specify the number of terms to sum in the series. As output, return the approximation to PI.

Exercise 3.
Repeat Exercise 3 of
MATLAB Programming I using your new function from Exercise 2.