Wichita State University Logo

M451: Computational Mathematics

2.1 Introduction to Functions in MATLAB


2.1.1 The MATLAB Language

MATLAB is an imperative programming language. Most MATLAB statements result in a change in the values stored in variables in the current scope . It may also result in creating or modifying other labels, modifying the configuration of the MATLAB interpreter, importing or exporting data, or changing the flow of execution of the interpreter. The MATLAB IDE, the MATLAB interpreter, the current workspace, and the process by which the MATLAB Interpreter parses MATLAB statements in the current scope and executes those instructions is called the state of the process. The MATLAB language is imperative because MATLAB statements utilize names to modify the state of the execution environment directly. The execution environment of most of the functions you will write in this class is the MATLAB Integrated Development Environment.

MATLAB is a procedural programming language. In computer functions are also referred to as procedures . All procedural programming languages are imperative. Programming statements in a procedural language utilize operators, keywords and procedure calls (funtions) to manipulate the state of the execution environment.

Within the imperative paradigm the MATLAB language is a procedural language. The MATLAB language is imperative because MATLAB statements explicitly modify the state of the execution environment.

>> x = 5

x =

       5       

>>

The MATLAB statement above may create a variable named x if it does not exist, and store the double precision floating point value of 5 in the memory location allocated for the variable. In this way the state of the execution environment has been modified directly by the programming statement.

We shall see in this chapter that MATLAB is a structured programming language. Structured programming is a paradigm that makes use of keywords to create well-defined flow of execution

  • when a decision algorithm element must choose one of many flows of execution,
  • when a group of statements are organized into a block that implements an element of an algorithm, or
  • when a block must be executed repetitively

The goal of structured programming

  • improve supportability of source code; that is make it easier to read and comprehend
  • improve the quality of source code; that is make it easier to write statements that faithfully and efficiently implement an algorithm
  • reduce the development time necessary to implement an algorithm
  • segregate tasks into sub-tasks to simplify development

2.1.2 Functions in MATLAB

In previous lectures, many built-in MATLAB functions have been used to perform various tasks, such as creating a matrix full of random entries and determining the maximum value of each column of a matrix.

The functions rand and max both have specific requirements for the number and type of inputs which are necessary for them to work properly. When given appropriate inputs, the functions return output values which are result of a specific set of computations performed on the input values. This is useful because it automates what may otherwise be a tedious or complicated task. MATLAB, and most programming languages in general, feature hundreds of built-in functions to automate tasks that will be performed many many times. In this section, we will begin to discuss the process of writing our own MATLAB functions.

Functions contain one or more MATLAB statements that implement an algorithm. These statements are collectively called the source code of the function. The MATLAB IDE uses an interpreter . The MATAB interpreter parses each MATLAB statement and executes the statement directly. This makes the MATLAB programming language an interpreted language . However, there is a MATLAB compiler capable of creating stand alone applications and web applications. The MATLAB compiler can also generate C or C++ version of the MATLAB source code that can be compiled by a C or C++ compiler.

In the same file as the source code one typically finds comments that detail the intention of the statements. These comments constitute internal documentation of the function. A comment is a programmer-readable explanation of the purpose of the function and the intent of the original developer.

Comments are typically organized into

  • a header
  • source comments
  • a trailer

The header supplies important information to any programmer who would want to use the function or script. The source comments are interspersed among the source code to help a reader understand the structure and implementation of the function. The trailer supplies important information to the organization that owns and/or maintains the source file.

2.1.3 Scope

Usually a function or MATLAB statement is not allowed to change every variable, or all possible labels, or any configuration of the MATLAB interpretor.

The range of possible values, labels, graphs, data, source code paths of execution, and configuration that a MATLAB function can affect is called the scope of the function. A variable, label, or statement may also have scope.

  • The scope of a label or variable is the set of functions or statements that have access to it.
  • The scope of a statement or function is the MATLAB elements and variables it can access.

Variables are organized by the MATLAB IDE into separate segments of memory called a workspace . A workspace contains all of the variables, their values, and data that you create or import from other data files or programs. Workspace values and variables are dynamic . They are lost when one exits the MATLAB environment. We say that these variables and data are not persistent . Data written to a file and saved is called persistent data . Persistent storage continues to hold values after the MATLAB environment terminates or the device is powered off.

The Base Workspace is the work space created by the MATLAB IDE for the command line environment. Variables created at the MATLAB command prompt reside in the base workspace. Although a programmer can perform all functions in the base workspace, it is generally discouraged. If a programmer writes several dozen programs for several different projects, keeping track of all of the variable names and their definitions would be very difficult. There would also be too many opportunities for source code from different projects to use the same label for variables or labels that have very different definitions or purposes. A name collision occurs when two or more processes use the same label in the same scope for different purposes. Name collisions can cause horrible and difficult to ascertain semantic defects or bugs .

The Global Workspace is the work space created by the MATLAB IDE for global labels . Global label, or global names, are labels that may be accessed by both the command line and functions. The global workspace has global scope ; that is everyone has access to it. The global workspace should be uses very sparingly as name collisions occur.

  • a name collision occurs when two different functions use the same global name for different purposes
  • a name collision occurs when a local name matches the global name and obscures the global one from use by the local function.

2.1.4 MATLAB Functions

MATLAB Functions have their own scope, and thus their own workspace. We call this function scope . When a MATLAB function is invoked, the first statement of the function declares the function, its inputs, and its outputs.

  • The inputs of a function are called its input parameters .
  • The outputs of a function are called its output parameters .

A MATLAB function may declare none or many input parameters, and none or many output parameters. When the MATLAB interpreter parses the first line of a function it creates a new local workspace or function workspace . The input and output parameters are defined in the local workspace and have function scope. That means they can only be accessed within the body of the function.

Statements in the function body may utilize names in the function workspace or the global workspace. This prevents name collisions with labels in the base workspace and other function workspaces. This allows a programmer to use familiar variable names for common implementations. For example $i$, $j$, and $k$ are often used as counter variables for loop structures.

A function workspace ceases to exist when the function terminates execution. Any name that must exist after the termination of the function should be created in the global workspace.

Use the global workspace SPARRINGLY . Creating global variables seems convenient to beginning programmers, however you should avoid the dark side and use LOCAL variables.

Using local variables frees the programmer from garbage collection . That is cleaning a large common workspace of temporary labels used only in a specific block of code. Function statements may create and use temporary names that will the cleared from the execution environment when the function terminates and the workspace cleared.

Using local variables allows for algorithms that create loops of execution that call the same function repeatedly. A new workspace is created each time the function is invoked so that several instances of the function may be executing at the same time without any name collisions. That is no name collisions for local variables . Using the global workspace for a function that may have several instances running simultaneously requires very careful programming and can be very difficult to maintain.

Although loops are a common way for a function to be invoked repeatedly, some functions have MATLAB statements that invoke the self-same function . Functions that invoke another instance of itself to implement an algorithm are called recursive functions . Recursive programming is an alternative to using loops to call the same function repeatedly. Each instance of a recursive function requires its own local workspace.

There are four basic types of MATLAB functions

2.1.5 MATLAB Scripts

A MATLAB M-file script is a named procedure . That means that the script is invoked using the filename of the M-file without any ".m" extension. The scope of a script is the MATLAB Search Path .

Figure 1

Any MATLAB function and the command window can invoke a script as long as the file is in the search path defined for the MATLAB IDE.

MATLAB Scripts run in the scope of the MATLAB statement that invokes it.

  1. A MATLAB script invoked from the command line uses the base workspace.

  2. A MATLAB script invoked in a function runs in function scope and uses the local workspace.

For this reason scripts have neither input parameters, nor output parameters. The programmer must create and properly initialize any variables required by the script in the appropriate workspace before invoking the script. Subsequent statements in the same block may utilize any names created by the script within that scope.

That is why it is important to include a header in your script so that a programmer who has the script file also has the documentation for using the script.

2.1.6 Anonymous Functions

The simplest function one can write in MATLAB is an anonymous function . An anonymous function is declared and defined in a single MATLAB command. The syntax for the MATLAB expression is

@(x1, x2, ..., xn)

Unlike all other methods of declaring a function, the anonymous function has no function name . Instead the MATLAB function handle operator @ is used to create a handle to the anonymous function.

  • An anonymous function may have any finite list of input parameters.
  • An anonymous function may have at most one output parameter.
  • The body of an anonymous function consists of only one MATLAB statement.
  • An anonymous function has its own scope and local workspace.

Remarks:

If an anonymous function has no inputs use empty parentheses to define and invoke the function.

>> format long
>> PI = @() 3.14159265358979323;
>> PI()

ans =

   3.141592653589793

>>

A single output may be an array.

>> parabola = @() [ 1, 2, 1 ];
>> parabola()

ans =

     1     2     1

>>

The definition of an anonymous function is its single MATLAB statement.

If one uses variables or mutable values in the definition of an anonymous function, then the definition of the anonymous function occurs when the declaration statement is executed. If the values used to define the anonymous function change, the definition of the anonymous function does not ! If you want to re-define the statement of the anonymous function, the declaration statement must be executed again.

In [5]:
figure;
hold on
for i=-10:10
    fplot(@(x) polyval([ 1 2 i ], x), [-10, 10])
end
hold off
axis([-8 8 -20 80])
title('Family of integral curves')

       

In the for loop above the definition of the anonymous function

@(x) polyval([1 2 i], [-10, 10])

relies on the value of variable i . However the anonymous function is redeclared and re-defined in each iteration of the loop. If we define the anonymous function outside of the loop,

In [6]:
figure;
hold on
i = -10;
curve = @(x) polyval([1 2 i], x);
for i=-10:10
    fplot(curve, [-10, 10])
end
hold off
axis([-8 8 -20 80])
title('Family of integral curves')

       

Even though the value of i changes in each iteration of the loop, the value of the variable when the anonymous function is defined is -10 . Since a new anonymous function is not created in each iteration of the loop, the definition of the anonymous function never changes. Note also that one must assign the value of the function handle to a variable in order to use the function handle in subsequent statements in the block.

2.1.7 Compute Number of Days

  1. Create a flow chart to illustrate your algorithm for completing the following:
  • Create an anonymous function that computes the number days from a given date string to today and assign the function handle to the variable totaldays
>> totaldays  = @(startdate) datenum(date) - datenum(startdate)

totaldays =

  function_handle with value:

    @(startdate)datenum(date)-datenum(startdate)

>>
  • In the script DaysOld.m prompt the user for their birth date in the format 'dd-mm-yyyy' using the MATLAB input function and assign the response to the variable birthdate .

  • Emit the total days from the birthdate until today using the MATLAB statement

    disp(' ')
    disp([ 'You are ' int2str(totaldays(birthdate)) ' days old today!' ])
    disp(' ')

Notice that you can create a character string using the array operators [ and ] . You just need to list the characters. The MATLAB function int2str converts the integer number of days returned by your anonymous function into a character array that we can use to define the whole message.

The output of your script DaysOld.m should look like,

>> DaysOld
What is your birth date? (dd-mmm-yyyy): '30-jan-1968'

You are 19943 days old today!

>>

Creative Commons Logo - White


Your use of this self-initiated mediated course material is subject to our Creative Commons License .


Creative Commons Attribution-NonCommercial-ShareAlike 4.0

Creative Commons Logo - Black
Attribution
You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.

Creative Commons Logo - Black
Noncommercial
You may not use the material for commercial purposes.

Creative Commons Logo - Black
Share Alike
You are free to share, copy and redistribute the material in any medium or format. If you adapt, remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.