MATLAB Tutorial of Fundamental Programming
MATLAB Tutorial of Fundamental Programming
Fundamental Programming
Prepared by:
Khairul Anuar Ishak
Department of Electrical, Electronic & System Engineering
Faculty of Engineering
Universiti Kebangsaan Malaysia
MATLAB tutorial of fundamental programming
Preface
This tutorial introduces the fundamental ideas for programming in MATLAB. The objective
is to help you at solving the kinds of mathematical problems that you will likely encounter as an
engineering student, as well as a researcher. It requires no prior knowledge of MATLAB or
programming experience but if you have a strong background in mathematics and computer
programming then you can quickly learn how MATLAB can help you with your course work
and design projects. However, for those of you who are just starting out learning MATLAB, then
this tutorial is for you.
Remember, it is assumed throughout all chapters that you are following along, using MATLAB
and entering all commands shown. The questions and answers of the exercises, will be given
during the workshop went off.
Notes: You can e-mail me if you have any problems or corrections about these pieces of code, or
if you would like to add your own tips to those described in this document.
i
MATLAB tutorial of fundamental programming
Contents
1 Introduction to MATLAB 1
What is MATLAB? 1
MATLAB System 2
The Advantages of MATLAB 2
Disadvantages of MATLAB 3
2 Getting Started 4
Starting MATLAB 4
Ending a Session 8
3 MATLAB Basics 9
Variables and Arrays 9
Arithmetic Operations 14
Common MATLAB Functions 16
4 Plotting and Visualization 17
Plotting in MATLAB 17
Images in MATLAB 24
5 Programming 25
Data Types 25
M-File Programming 27
Flow Control 30
ii
CHAPTER 1: Introduction to MATLAB
What is MATLAB?
CHAPTER 1
Introduction to MATLAB
What is MATLAB?
MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program in
a scalar non-interactive language such as C, C++ or Fortran.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering and science. In industry, MATLAB is the tool of choice for high-
productivity research, development and analysis.
1
CHAPTER 1: Introduction to MATLAB
MATLAB System
MATLAB System
1. The MATLAB language. This is a high-level matrix/array language with control flow
statements, functions, data structures, input/output, and object-oriented programming
features. It allows both “programming in the small” to rapidly create quick and dirty
throw-away programs, and “programming in the large” to create complete large and
complex application programs.
2. The MATLAB working environment. This is the set of tools and facilities that you
work with as the MATLAB user or programmer. It includes facilities for managing the
variables in your workspace and importing and exporting data. It also includes tools for
developing, managing, debugging, and profiling M-files, MATLAB’s applications.
3. Handle Graphics. This is the MATLAB graphics system. It includes high-level
commands for two-dimensional and three-dimensional data visualization, image
processing, animation, and presentation graphics. It also includes low-level commands
that allow you to fully customize the appearance of graphics as well as to build complete
Graphical User Interfaces on your MATLAB applications.
4. The MATLAB mathematical function library. This is a vast collection of
computational algorithms ranging from elementary functions like sum, sine, cosine, and
complex arithmetic, to more sophisticated functions like matrix inverse, matrix
eigenvalues, Bessel functions, and fast Fourier transforms.
5. The MATLAB Application Program Interface (API). This is a library that allows you
to write C and Fortran programs that interact with MATLAB. It include facilities for
calling routines from MATLAB (dynamic linking), calling MATLAB as a computational
engine, and for reading and writing MAT-files.
MATLAB has many advantages compared to conventional computer languages for technical
problem solving. Among them are:
1. Ease of Use. MATLAB is an interpreted language. Program may be easily written and
modified with the built-in integrated development environment and debugged with the
MATLAB debugger. Because the language is so easy to use, it is ideal for the rapid
prototyping of new programs.
2. Platform Independence. MATLAB is supported on many different computer systems,
providing a large measure of platform independence. At the time of this writing, the
language is supported on Windows NT/2000/XP, Linux, several versions of UNIX and
the Macintosh.
3. Predefined Function. MATLAB comes complete with an extensive library of predefined
functions that provide tested and pre-packaged solutions to many basic technical tasks.
For examples, the arithmetic mean, standard deviation, median, etc. these and hundreds
of other functions are built right into the MATLAB language, making your job much
easier. In addition to the large library of function built into the basic MATLAB language,
2
CHAPTER 1: Introduction to MATLAB
Disadvantages of MATLAB
there are many special-purpose toolboxes available to help solve complex problems in
specific areas. There is also an extensive collection of free user-contributed MATLAB
programs that are shared through the MATLAB Web site.
4. Device-Independent Plotting. Unlike most other computer languages, MATLAB has
many integral plotting and imaging commands. The plots and images can be displayed on
any graphical output device supported by the computer on which MATLAB is running.
5. Graphical User Interface. MATLAB includes tools that allow a programmer to
interactively construct a graphical user interface, (GUI) for his or her program. With this
capability, the programmer can design sophisticated data-analysis programs that can be
operated by relatively inexperienced users.
6. MATLAB Compiler. MATLAB’s flexibility and platform independence is achieved by
compiling MATLAB programs into a device-independent p-code, and then interpreting
the p-code instructions at runtime. Unfortunately, the resulting programs can sometimes
execute slowly because the MATLAB code is interpreted rather than compiled.
Disadvantages of MATLAB
MATLAB has two principal disadvantages. The first is that it is an interpreted language and
therefore can execute more slowly than compiled languages. This problem can be mitigated by
properly structuring the MATLAB program, and by the use of the MATLAB compiler to
compile the final MATLAB program before distribution and general use.
The second disadvantage is cost: a full copy of MATLAB is five to ten times more expensive
than a conventional C or Fortran compiler. This relatively high cost is more than offset by then
reduced time required for an engineer or scientist to create a working program, so MATLAB is
cost-effective for businesses. However, it is too expensive for most individuals to consider
purchasing. Fortunately, there is also an inexpensive Student Edition of MATLAB, which is a
great tool for students wishing to learn the language. The Student Edition of MATLAB is
essentially identical to the full edition.
3
CHAPTER 2: Getting Started
Starting MATLAB
CHAPTER 2
Getting Started
Starting MATLAB
You can start MATLAB by double-clicking on the MATLAB icon or invoking the
application from the Start menu of Windows. The main MATLAB window, called the
MATLAB Desktop, will then pop-up and it will look like this:
When MATLAB executes, it can display several types of windows that accept commands or
display information. It integrates many tools for managing files, variables and applications within
the MATLAB environment. The major tools within or accessible from the MATLAB desktop
are:
4
CHAPTER 2: Getting Started
Starting MATLAB
If desired, this arrangement can be modified by selecting an alternate choice from [View] Ö
[Desktop Layout]. By default, most MATLAB tools are “docked” to the desktop, so that they
appear inside the desktop window. However, you can choose to “undock” any or all tools,
making them appear in windows separate from the desktop.
The Command Window is where the command line prompt for interactive commands is
located. Once started, you will notice that inside the MATLAB command window is the text:
>>
Click in the command window to make it active. When a window becomes active, its titlebar
darkens. The “>>” is called the Command Prompt, and there will be a blinking cursor right after
it waiting for you to type something. You can enter interactive commands at the command
prompt (>>) and they will be executed on the spot.
As an example, let’s enter a simple MATLAB command, which is the date command. Click
the mouse where the blinking cursor is and then type date and press the ENTER key. MATLAB
should then return something like this:
>> date
ans =
01-Sep-2006
Where the current date should be returned to you instead of 01-Sep-2006. Congratulation!
You have just successfully executed your first MATLAB command!
5
CHAPTER 2: Getting Started
Starting MATLAB
The Command History Window, contains a log of commands that have been executed within
the command window. This is a convenient feature for tracking when developing or debugging
programs or to confirm that commands were executed in a particular sequence during a multi-
step calculation from the command line.
The Current Directory Browser displays a current directory with a listing of its contents.
There is navigation capability for resetting the current directory to any directory among those set
in the path. This window is useful for finding the location of particular files and scripts so that
they can be edited, moved, renamed or deleted. The default directory is the Work subdirectory of
the original MATLAB installation directory.
6
CHAPTER 2: Getting Started
Starting MATLAB
The Workspace Window provides an inventory of all the items in the workspace that are
currently defined, either by assignment or calculation in the Command Window or by importing
with a load or similar command from the MATLAB command line prompt. These items consist
of the set of arrays whose elements are variables or constants and which have been constructed or
loaded during the current MATLAB session and have remained stored in memory. Those which
have been cleared and no longer are in memory will not be included. The Workspace Window
shows the name of each variable, its value, its array size, its size in bytes, and the class. Values of
a variable or constant can be edited in an Array Editor which is launched by double clicking its
icon in the Workspace Window.
7
CHAPTER 2: Getting Started
Ending a Session
You can access the online help in one of several ways. Typing help at the command prompt
will reveal a long list of topics on which help is available. Just to illustrate, try typing help
general. Now you see a long list of “general purpose” MATLAB commands. In addition, you
can also get help on the certain command. For example, date command. The output of help also
refers to other functions that are related. In this example the help also tells you, See also NOW,
CLOCK, DATENUM. You can now get help on these functions using the three different commands
as well.
There is a much more user-friendly way to access the online help, namely via the MATLAB
Help Browser. Separate from the main desktop layout is a Help desktop with its own layout. This
utility can be launched by selecting [Help] Ö [MATLAB Help] from the Help pull down menu.
This Help desktop has a right side which contains links to help with functions, help with
graphics, and tutorial type documentation.
Interrupting Calculations
If MATLAB is hung up in a calculation, or is just taking too long to perform an operation,
you can usually abort it by typing [CTRL + C] (that is, hold down the key labeled CTRL, and press
C).
Ending a Session
One final note, when you are all done with your MATLAB session you need to exit
MATLAB. To exit MATLAB, simply type quit or exit at the prompt. You can also click on the
special symbol that closes your windows (usually an × in the upper right-hand corner). Another
way to exit is by selecting [File] Ö [Exit MATLAB]. Before you exit MATLAB, you should be
sure to save any variables, print any graphics or other files you need, and in general clean up
after yourself.
8
CHAPTER 3: MATLAB Basics
Variables and Arrays
CHAPTER 3
MATLAB Basics
The fundamental unit of data in any MATLAB program is the array. An array is a collection
of data values organized into rows and columns and known by a single name. Individual data
values within an array are accessed by including the name of the array followed by subscripts in
parentheses that identify the row and column of the particular value. Even scalars are treated as
arrays by MATLAB – they are simply arrays with only one row and one column. There are three
fundamental concepts in MATLAB, and in linear algebra, are scalars, vectors and matrices.
⎡1⎤
This is a 3×1 array containing 3 elements, known as a column vector
c = ⎢⎢2⎥⎥
⎢⎣3⎥⎦
In MATLAB matricies are defined inside a pair of square braces ([]). Punctuation marks of a
comma (,), and semicolon (;) are used as a row separator and column separator, respectfully.
You can also use a space as a row separator, and a carriage return (the ENTER key) as a column
separator as well.
9
CHAPTER 3: MATLAB Basics
Variables and Arrays
Examples 3.1
Below are examples of how a scalar, vector and matrix can be created in MATLAB.
>> my_scalar = 3.1415
my_scalar =
>> my_vector1 = [1 5 7]
3.1415
my_vector1 =
>> my_vector1 = [1, 5, 7]
1 5 7
my_vector1 =
1 5 7
>> my_vector2 = [1
5
>> my_vector2 = [1; 5; 7] 7]
my_vector2 = my_vector2 =
1 1
5 5
7 7
my_matrix =
8 12 19
7 3 2
12 4 23
8 1 1
Row 1 A 2-by-3
Matrix
Row 2
Figure 3.1: An array is a collection of data values organized into rows and columns
10
CHAPTER 3: MATLAB Basics
Variables and Arrays
Individual elements in an array are addressed by the array name followed by the row and
column of the particular element. If the array is a row or column vector, then only one subscript
is required. For example, according to the example 3.1:
o my_vector2(2) is 5
o my_matrix(3,2) is 4 or my_matrix(7) is 4
Examples 3.2
[ 1 2 3 4 5 6 7] [ 1 3 5 7] [ 5 3 1]
my_matrix =
8 12 19
7 3 2
12 4 23
8 1 1
new_matrix1 =
12 19
3 2
4 23
new_matrix2 =
12 4 23
8 1 1
∗ NOTES: If the colon is used by itself within subscript, it refers to all the elements in a row or
column of a matrix!
11
CHAPTER 3: MATLAB Basics
Variables and Arrays
Concatenating Matrices
Matrix concatenation is the process of joining one or more matrices to make a new matrix.
The expression C = [A B] horizontally concatenates matrices A and B. The expression C = [A;
B] vertically concatenates them.
Examples 3.3
>> A = [8 19; 7 2];
>> B = [1 64; 4 5; 3 78];
>> C = [A; B]
C =
8 19
7 2
1 64
4 5
3 78
Reshaping a Matrix
Here are a few examples to illustrate some of the ways you can reshape matrices.
Examples 3.4
A =
1 4 7 10
2 5 8 11
3 6 9 12
>> B = reshape(A, 2, 6)
B =
1 3 5 7 9 11
2 4 6 8 10 12
12
CHAPTER 3: MATLAB Basics
Variables and Arrays
Examples 3.5
Transpose A so that the row elements become columns or vice versa. You can use either the
transpose function or the transpose operator (’). To do this:
B =
1 2 3
4 5 6
7 8 9
10 11 12
MATLAB includes a number of built-in functions that you can use to determine a number of
characteristics of a vector. The following are the most commonly used such functions.
Examples 3.6
13
CHAPTER 3: MATLAB Basics
Arithmetic Operations
This following section summarizes the principal functions used in creating and handling
matrices. Most of these functions work on multi-dimensional arrays as well.
Examples 3.7
A = C =
B =
7 7 7
Arithmetic Operations
MATLAB can be used to evaluate simple and complex mathematical expressions. When we
move from scalars to vectors (and matrices), some confusion arises when performing arithmetic
operations because we can perform some operations either on an element-by-element (array
operation) or matrices as whole entities (matrix operation). Expressions use familiar
arithmetic operators:
Array Operators
Operation MATLAB Form Comments
Addition A + B Array addition is identical
Subtraction A - B Array subtraction is identical
Multiplication A .* B Element-by-element multiplication of A and B. Both
arrays must be the same shape, or one of them must
be a scalar
Division A ./ B Element-by-element division of A and B. Both arrays
must be the same shape, or one of them must be a
scalar
14
CHAPTER 3: MATLAB Basics
Arithmetic Operations
Examples 3.8
1 4 7 10 1 4 9 16
2 5 8 11
3 6 9 12
>> A = [ 2 4 ; 8 10]
>> B = [1 2 3 4; 5 6 7 8; 9 10 11 12] A =
B = 2 4
8 10
1 2 3 4
5 6 7 8 >> B = [2 4; 2 5]
9 10 11 12 B =
>> C = A.*B 2 4
2 5
C =
>> C = A./B
1 8 21 40 C =
10 30 56 88
27 60 99 144 1 1
4 2
Matrix Operators
Operation MATLAB Form Comments
Addition A + B Array addition is identical
Subtraction A - B Array subtraction is identical
Multiplication A * B Matrix multiplication of A and B. The number of
columns in A must equal the number of rows in B.
Division A / B Matrix division defined by A * inv(B), where
inv(B) is the inverse of matrix B.
Power A ^ B Matrix exponentiation of A and B. The power is
computed by repeated squaring
Examples 3.9
>> A = [ 2 4 ; 8 10]; >> A = [ 2 4 ; 8 10];
>> B = [2 4; 2 5]; >> B = [2 4; 2 5];
>> C = A*B >> C = B*A
C = C =
12 28 36 48
36 82 44 58
15
CHAPTER 3: MATLAB Basics
Common MATLAB Functions
Built-in Variables
MATLAB uses a small number of names for built-in variables. An example is the ans
variable, which is automatically created whenever a mathematical expression is not assigned to
another variable. Table below lists the built-in variables and their meanings. Although you can
reassign the values of these built-in variables, it is not a good idea to do so, because they are used
by the built-in functions.
Variable Meaning
ans Value of an expression when that expression is not assigned to a variable
eps Floating-point precision
Unit imaginary number, i = j = −1
i,j
pi π , 3.14159265 …
realmax Largest positive floating-point number
realmin Smallest positive floating-point number
Inf 1
∞ , a number larger than realmax, the result of evaluating
0
NaN 0
Not a number, (e.g., the result of evaluating
0
Examples 3.10
>> x = 0; >> x = 0;
>> 5/x >> x/x
16
CHAPTER 3: MATLAB Basics
Common MATLAB Functions
Examples 3.11
>> whos >> str = [‘MATLAB Baguss..!’];
Name Size Bytes Class >> disp(str);
ans 1x1 226 sym object
y 1x1 8 char array MATLAB Baguss..!
v 4x5 200 double array
x 1x3 500 double array
Examples 3.12
>> z = 2*sin(pi/2)+log(2) >> z = 2*sin(pi/2)+log(2)
z = z =
2.6931 2.6931
z = z =
3 3
17
CHAPTER 4: Plotting and Visualization
Plotting in MATLAB
CHAPTER 4
Plotting and Visualization
Plotting in MATLAB
MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as
annotating and printing these graphs. This section describes a few of the most important graphics
functions and provides examples of some typical applications.
Creating a Plot
The plot function has different forms, depending on the input arguments. If y is a vector,
plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements
of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.
For example, to plot the value of the sine function from zero to 2π, use:
Examples 4.1
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y);
18
CHAPTER 4: Plotting and Visualization
Plotting in MATLAB
This is the basic command of plotting a graph. Besides that, MATLAB has commands which
will let you add titles and labels and others in order to make your figures more readable.
However, you need to keep the figure window open while executing these commands.
>> xlabel(‘Radian’);
>> ylabel(‘Amplitude’);
>> title(‘Plot of sin(x) vs x’);
>> grid on;
The current limits of this plot can be determined from the basic axis function. So, in order to
modify the x-axis within [0 2π], you need to run this function:
19
CHAPTER 4: Plotting and Visualization
Plotting in MATLAB
Annotating Plots
You can adjust the axis tick-mark locations and the labels appearing at each tick mark. For
example, this plot of the sine function relabels the x-axis with more meaningful values.
Example 4.2
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y);
>> set(gca,’XTick’,-pi:pi/2:pi);
>> set(gca,’XTickLabel’,{‘-pi’,’-pi/2’,’0’,’pi/2’,’pi’});
>> xlabel('-\pi \leq \Theta \leq \pi');
>> ylabel('sin(\Theta)');
>> title('Plot of sin(\Theta)');
Semilogarithmic plot is another type of figuring a graph by rescaling if the new data falls
outside the range of the previous axis limits.
Example 4.3
>> x = linspace(0,3);
>> y = 10*exp(-2*x);
>> semilogy(x,y);
>> grid on;
20
CHAPTER 4: Plotting and Visualization
Plotting in MATLAB
You can control a number of line style characteristics by specifying values for line properties.
Example 4.4
>> x = -pi:pi/10:pi;
>> y = tan(sin(x)) - sin(tan(x));
>> plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g','MarkerSize',10);
Multiple Plots
Often, it is desirable to place more than one plot in a single figure window. This is achieved
by three ways:
The subplot Function breaks the figure window into an m-by-n matrix of small subplots and
selects the ith subplot for the current plot. The plots are numbered along the top row of the figure
window, then the second row, and so forth.
21
CHAPTER 4: Plotting and Visualization
Plotting in MATLAB
Example 4.5
>> x = linspace(0,2*pi);
>> subplot(2,2,1);
>> plot(x,sin(x));
>>
>> subplot(2,2,2)
>> plot(x,sin(2*x));
>>
>> subplot(2,2,3)
>> plot(x,sin(3*x));
>>
>> subplot(2,2,4)
>> plot(x,sin(4*x));
Multiple plots
You can assign different line styles to each data set by passing line style identifier strings to
plot and placing a legend on the plot to identify curves drawn with different symbol and line
types.
Example 4.6
>> x = linspace(0,2*pi);
>> y1 = sin(x);
>> y1 = cos(x);
>> y1 = tan(x);
>> plot(x,y1,x);
>> axis([0 2*pi -1 1]);
The hold command will add new plots on top of previously existing plots.
Example 4.6
>> x = -pi:pi/20:pi;
>> y1 = sin(x);
>> y2 = cos(x);
>> plot(x,y1,'b-');
>> hold on;
>> plot(x,y2,'g--');
>> hold off;
>> legend('sin(x)','cos(x)');
22
CHAPTER 4: Plotting and Visualization
Plotting in MATLAB
Example 4.7
Example 4.8
23
CHAPTER 4: Plotting and Visualization
Images in MATLAB
Images in MATLAB
The basic data structure in MATLAB is the array, an ordered set of real or complex
elements. Thus, MATLAB stores most images as two-dimensional arrays (i.e., matrices), in
which each element of the matrix corresponds to a single pixel in the displayed image. For
example, an image composed of 200 rows and 300 columns or different colored dots would be
stored in MATLAB as a 200-by-300 matrix. Some images, such as RGB, require a three-
dimensional array, where the first plane in the third dimension represents the red pixel intensities,
the second plane represents the green pixel intensities, and the third plane represents the blue
pixel intensities.
This example reads an 8-bit RGB image into MATLAB and converts it to a grayscale image.
Example 4.9
24
CHAPTER 5: Programming
Data Types
CHAPTER 5
Programming
Data Types
There are many different types of data that you can work with in MATLAB. You can build
matrices and arrays of floating point and integer data, characters and strings, logical true and
false states, etc. you can also develop your own data types using MATLAB classes. Two of the
MATLAB data types, structures and cell arrays, provide a way to store dissimilar types of data in
the same array.
There are 15 fundamental data types (or classes) in MATLAB. Each of these data types is in
the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-dimensional
array of any size. Two-dimensional versions of these arrays are called matrices. All of the
fundamental data types are shown in lowercase text in the diagram below. Additional data types
are user-defined, object-oriented user classes (a subclass of structure), and java classes, that you
can use with the MATLAB interface to Java. Matrices of type double and logical may be either
full or sparse. For matrices having a small number of nonzero elements, a sparse matrix requires
a fraction of the storage space required for an equivalent full matrix. Sparse matrices invoke
special methods especially tailored to solve sparse problems.
ARRAY
(full or sparse)
int8, unit8,
single double
int16, uint16,
int32, uint32,
int64, uint64
25
CHAPTER 5: Programming
26
CHAPTER 5: Programming
M-File Programming
MATLAB provides a full programming language that enables you to write a series of
MATLAB statements into a file and then execute them with a single command. You write your
program in an ordinary text file, giving the file a name of filename.m. The term you use for
filename becomes the new command that MATLAB associates with the program. The file
extension of .m makes this a MATLAB M-file. M-files can be scripts that simply execute a series
of MATLAB statements, or they can be functions that also accept arguments and produce output.
You create M-files using a text editor, then use them as you would any other MATLAB function
or command. The process looks like this:
Kinds of M-files
There are two kinds of M-files
27
CHAPTER 5: Programming
Scripts
Scripts are the simplest kind of M-file because they have no input or output arguments.
They're useful for automating series of MATLAB commands, such as computations that you
have to perform repeatedly from the command line. Scripts operate on existing data in the
workspace, or they can create new data on which to operate. Any variables that scripts create
remain in the workspace after the script finishes so you can use them for further computations.
Example 5.1
Try entering these commands in an M-file called petals.m. This file is now a MATLAB
script. Typing petals at the MATLAB command line executes the statements in the script.
28
CHAPTER 5: Programming
Functions
Functions are M-files that accept input arguments and return output arguments. They operate
on variables within their own workspace. This is separate from the workspace you access at the
MATLAB command prompt.
Example 5.2
function y = average(x)
% AVERAGE Mean of vector elements.
% AVERAGE(X), where X is a vector, is the mean of vector elements.
% Nonvector input results in an error.
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))
error('Input must be a vector')
end
If you would like, try entering these commands in an M-file called average.m. The average
function accepts a single input argument and returns a single output argument. To call the
average function, enter
>> z = 1:99;
>> average(z)
ans =
50
The function definition line informs MATLAB that the M-file contains a function, and
specifies the argument calling sequence of the function. The function definition line for the
average function is
29
CHAPTER 5: Programming
All MATLAB functions have a function definition line that follows this pattern.
The Function Name - MATLAB function names have the same constraints as variable
names. The name must begin with a letter, which may be followed by any combination of letters,
digits, and underscores. Making all letters in the name lowercase is recommended as it makes
your M-files portable between platforms.
Flow Control
1. if
2. continue
3. break
4. switch and case
5. for
6. while
If
The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The optional elseif and else keywords provide for the execution of alternate
groups of statements. An end keyword, which matches the if, terminates the last group of
statements. The groups of statements are delineated by the four keywords--no braces or brackets
are involved.
IF expression
statements
ELSEIF expression
statements
ELSE
statements
END
Continue
The continue statement passes control to the next iteration of the for or while loop in
which it appears, skipping any remaining statements in the body of the loop. In nested loops,
continue passes control to the next iteration of the for or while loop enclosing it.
Break
The break statement lets you exit early from a for or while loop. In nested loops, break exits
from the innermost loop only.
30
CHAPTER 5: Programming
The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching case
is executed. There must always be an end to match the switch.
SWITCH expression
CASE expression
statements
CASE expression
statements
OTHERWISE
statements
END
For
The for loop repeats a group of statements a fixed, predetermined number of times. A
matching end delineates the statements.
While
The while loop repeats a group of statements an indefinite number of times under control of a
logical condition. A matching end delineates the statements.
WHILE expression
Statements
END
31