0% found this document useful (0 votes)
9 views67 pages

Intro Matlab Application

This document serves as an introductory tutorial for MATLAB, emphasizing hands-on learning and the software's capabilities in numerical computations and matrix operations. It covers starting and quitting MATLAB, navigating the MATLAB desktop, and using various tools such as the Command Window and Help Browser. Additionally, it explains basic operations, variable creation, and error handling, along with the importance of operator precedence in calculations.

Uploaded by

nkamkacyn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views67 pages

Intro Matlab Application

This document serves as an introductory tutorial for MATLAB, emphasizing hands-on learning and the software's capabilities in numerical computations and matrix operations. It covers starting and quitting MATLAB, navigating the MATLAB desktop, and using various tools such as the Command Window and Help Browser. Additionally, it explains basic operations, variable creation, and error handling, along with the importance of operator precedence in calculations.

Uploaded by

nkamkacyn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

1 Chapter 1

1.1 Tutorial lessons 1

1.1.1 Introduction
The primarily objective is to help you learn quickly the first steps. The emphasis here is “learning by
doing”. Therefore, the best way to learn is by trying it yourself. Working through the examples will give you
a feel for the way that MATLAB operates. In this introduction we will describe how MATLAB handles
simple numerical expressions and mathematical formulas.

The name MATLAB stands for MATrix LABoratory. MATLAB was written originally to provide
easy access to matrix software developed by the LINPACK (linear system package) and EISPACK (Eigen
system package) projects.

The basic building block in MATLAB is the matrix. The fundamental data type is the array. Vectors,
scalars, real and complex matrices are all automatically handled as special cases of basic arrays. The built-
in functions are optimized for vector operations. Thus, vectorized commands or codes run much faster in
MATLAB (vectorization is a way of computing in which an operation is performed simultaneously on a list
of numbers rather than sequentially on each member of the list).

A nice thing to realize is that MATLAB is primarily a numerical computation package, although with
the 'Symbolic' Toolbox it can do also symbolic algebra. Mathematica, Maple, and Macsyma are primarily
symbolic algebra packages. MATLAB's ease of use is its best feature since you can have more learning with
less effort, while the computer algebra systems have a steeper learning curve.

In mathematical computations, especially those that utilize vectors and matrices, MATLAB is better
in terms of ease of use, availability of built-in functions, ease of programming, and speed. MATLAB's
popularity today has forced such packages as Macsyma and Mathematica to provide extensions for files in
MATLAB's format.

There are numerous prepared commands for 2D and 3D graphics as well as for animation. The
user is not limited to the built-in functions; he can write his own functions in MATLAB language. Once
written, these functions work just like the internal functions. MATLAB's language is designed to be easy to
learn and use.

The many built-in functions provide excellent tools for linear algebra, signal processing, data
analysis, optimization, solution of ordinary differential equations (ODEs), and many other types of scientific
operations.

There are also several optional 'toolboxes' available which are collections of functions written for
special applications such as 'Image Processing', 'Statistics', 'Neural Networks', etc.

1
The software package has been commercially available since 1984 and is now considered as a standard
tool at most universities and industries worldwide.

2
1.2 Starting and Quitting MATLAB

1.2.1 Starting MATLAB


On a Microsoft Windows platform, to start MATLAB, double-click the MATLAB shortcut icon
on your Windows desktop.

On Linux, to start MATLAB, type matlab at the operating system prompt.

After starting MATLAB, the MATLAB desktop opens – see “MATLAB Desktop”.

You can change the directory in which MATLAB starts, define startup options including running a
script upon startup, and reduce startup time in some situations.

1.2.2 Quitting MATLAB


To end your MATLAB session, select Exit MATLAB from the File menu in the desktop, or type
quit in the Command Window. To execute specified functions each time MATLAB quits, such as saving the
workspace, you can create and run a finish.m script.

1.3 MATLAB Desktop


When you start MATLAB, the MATLAB desktop appears, containing tools (graphical user
interfaces)
for managing files, variables, and applications associated with MATLAB.

The first time MATLAB starts, the desktop appears as shown in the following illustration, although
your Launch Pad may contain different entries.

3
Figure 1: The graphical interface to the MATLAB workspace.
You can change the way your desktop looks by opening, closing, moving, and resizing the tools in
it. You can also move tools outside of the desktop or return them back inside the desktop (docking). All the
desktop tools provide common features such as context menus and keyboard shortcuts.

You can specify certain characteristics for the desktop tools by selecting Preferences from the File
menu. For example, you can specify the font characteristics for Command Window text. For more information,
click the Help button in the Preferences dialog box as shown in Figure 2.

4
Figure 2:
Customization

1.4 Desktop Tools


This section provides an introduction to MATLAB’s desktop tools. You can also use
MATLAB
functions to perform most of the features found in the desktop tools. The tools are:

• Command Window”.
• Command History.
• Launch Pad
• Help Browser.
• Current Directory Browser.
• Workspace Browser.
• Array Editor.
• Editor/Debugger.

1.4.1 Command Window


Use the Command Window to enter variables and run functions and M-files.

5
Figure 3: Command
Window.

1.4.2 Command History


Lines you enter in the Command Window are logged in the Command History window. In the
Command History, you can view previously used functions, and copy and execute selected lines.

Figure 4: Command
History.

To save the input and output from a MATLAB session to a file, use the diary function.
6
Running External Programs

You can run external programs from the MATLAB Command Window. The exclamation point
character ! is a shell escape and indicates that the rest of the input line is a command to the operating system.
This is useful for invoking Timestamp marks the start of each session.

Select one or more lines and right-click to copy, evaluate, or create an M-file from the selection.
utilities or running other programs without quitting MATLAB. On Linux, for example,

!emacs magik.m

invokes an editor called emacs for a file named magik.m. When you quit the external program, the
operating system returns control to MATLAB.

1.4.3 Launch Pad


MATLAB’s Launch Pad provides easy access to tools, demos, and documentation.

Figure 5: Launch
Pad.

1.4.4 Help Browser


Use the Help browser to search and view documentation for all MathWorks products. The Help
browser is a Web browser integrated into the MATLAB desktop that displays HTML documents.

To open the Help browser, click the help button in the toolbar, or type helpbrowser in the
Command Window.

7
Figure 6: Help
Browser

1.4.5 Current Directory Browser


MATLAB file operations use the current directory and the search path as reference points. Any file
you want to run must either be in the current directory or on the search path.

A quick way to view or change the current directory is by using the Current Directory field in the
desktop toolbar as shown below.

Figure 7: Current Directory


Browser.
To search for, view, open, and make changes to MATLAB-related directories and files, use the
MATLAB Current Directory browser. Alternatively, you can use the functions dir, cd, and delete.

8
Figure 8: Current Directory
Browser.

Search Path

To determine how to execute functions you call, MATLAB uses a search path to find M-files and
other MATLAB-related files, which are organized in directories on your file system. Any file you want to run
in MATLAB must reside in the current directory or in a directory that is on the search path. By default, the
files supplied with MATLAB and MathWorks toolboxes are included in the search path.

To see which directories are on the search path or to change the search path, select Set Path from the
File menu in the desktop, and use the Set Path dialog box. Alternatively, you can use the path function to view
the search path, addpath to add directories to the path, and rmpath to remove directories from the path.

1.4.6 Workspace Browser


The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB
session and stored in memory. You add variables to the workspace by using functions, running M-files, and
loading saved workspaces.

To view the workspace and information about each variable, use the Workspace browser, or use the
functions who and whos.

To delete variables from the workspace, select the variable and select Delete from the Edit menu.
Alternatively, use the clear function.

9
The workspace is not maintained after you end the MATLAB session. To save the workspace to a
file that can be read during a later MATLAB session, select Save Workspace As from the File menu, or use
the save function. This saves the workspace to a binary file called a MAT-file, which has a .mat extension.
There are options for saving to different formats. To read in a MAT-file, select Import Data from the File
menu, or use the load function.

Figure 9: Workspace
Browser.

Array Editor

Double-click on a variable in the Workspace browser to see it in the Array Editor. Use the Array
Editor to view and edit a visual representation of one- or two-dimensional numeric arrays, strings, and cell
arrays of strings that are in the workspace.

10
Figure 10: Array
Editor.

11
1.4.7 Editor/Debugger
Use the Editor/Debugger to create and debug M-files, which are programs you write to run
MATLAB functions. The Editor/Debugger provides a graphical user interface for basic text editing, as well
as for M-file debugging.

Figure 11:
Editor/Debugger.
You can use any text editor to create M-files, such as Emacs, and can use preferences (accessible from
the desktop File menu) to specify that editor as the default. If you use another editor, you can still use the
MATLAB Editor/ Debugger for debugging, or you can use debugging functions, such as dbstop, which
sets a breakpoint.

If you just need to view the contents of an M-file, you can display it in the Command Window by
using the type function.

12
1.5 Getting started
Now, we are interested in doing some simple calculations. We will assume that you have sufficient
understanding of your computer under which MATLAB is being run.

You are now faced with the MATLAB desktop on your computer, which contains the prompt (>>)
in the Command Window. Usually, there are 2 types of prompt:

>> for full version

EDU> for educational version

Note: To simplify the notation, we will use this prompt, >>, as a standard prompt sign, though our
MATLAB version is for educational purpose.

1.5.1 Using MATLAB as a calculator


As an example of a simple interactive calculation, just type the expression you want to evaluate.
Let’s start at the very beginning. For example, let’s suppose you want to calculate the expression,
You type it at the prompt command (>>) as follows,

>> 1+2*3

ans =

You will have noticed that if you do not specify an output variable, MATLAB uses a default variable
‘ans’, short for answer, to store the results of the current calculation. Note that the variable ‘ans’ is created (or
overwritten, if it is already existed). To avoid this, you may assign a value to a variable or output argument
name. For example,

>> x = 1+2*3

x =

will result in x being given the value . This variable name can always be used
to refer to the results of the previous computations. Therefore, computing 4x will result in

>> 4*x

ans =

28.0000

Before we conclude this minimum session, Table 1.1 gives the partial list of commonly used
MATLAB operators and special characters used to solve many engineering and science problems.

13
Table 1: Operators and special Characteristics

After learning the minimum MATLAB session, we will now learn to use some additional operations.

1.5.2 Creating MATLAB variables


MATLAB variables are created with an assignment statement. The syntax of variable assignment is
variable name = a value (or an expression)

For example,

>> x = expression

where expression is a combination of numerical values, mathematical operators, variables, and


function calls. On other words, expression can involve:

• manual entry
• built-in functions
• user-defined functions

14
1.5.3 Overwriting variable
Once a variable has been created, it can be reassigned. In addition, if you do not wish to see the
intermediate results, you can suppress the numerical output by putting a semicolon (;) at the end of the line.
Then the sequence of commands looks like this:
>> t = 5;

>> t = t+1

t =

1.5.4 Error messages


If we enter an expression incorrectly, MATLAB will return an error message. For example, in the
following, we left out the multiplication sign, *, in the following expression

>> x = 10;

>> 5x

??? 5x

Error: Unexpected MATLAB expression.

1.5.5 Making corrections


To make corrections, we can, of course retype the expressions. But if the expression is lengthy, we
make more mistakes by typing a second time. A previously typed command can be recalled with the up- arrow
key ↑. When the command is displayed at the command prompt, it can be modified if needed and executed.

1.5.6 Controlling the hierarchy of operations or precedence


Let’s consider the previous arithmetic operation, but now we will include parentheses. For
example, will become

>> (1+2)*3

ans =

and, from previous example

15
>> 1+2*3

ans =

By adding parentheses, these two expressions give different results: 9 and 7.

The order in which MATLAB performs arithmetic operations is exactly that taught in high school
algebra courses. Exponentiations are done first, followed by multiplications and divisions, and finally by
additions and subtractions. However, the standard order of precedence of arithmetic operations can be
changed by inserting parentheses. For example, the result of is quite different than the similar
expression with parentheses . The results are 7 and 9 respectively. Parentheses can always
be used to overrule priority, and their use is recommended in some complex expressions to avoid ambiguity.

Therefore, to make the evaluation of expressions unambiguous, MATLAB has estab- lished a series
of rules. The order in which the arithmetic operations are evaluated is given in Table 2Table 2. MATLAB
arithmetic operators obey the same precedence rules as those in

Table 2: Hierarchy of arithmetic


operations.

Precedence Mathematical operations

First The contents of all parentheses are evaluated first, starting from the innermost
parentheses and working outward.
Second All exponentials are evaluated, working from left to right
Third All multiplications and divisions are evaluated, working from left to right
Fourth All additions and subtractions are evaluated, starting from left to right
most computer programs. For operators of equal precedence, evaluation is from left to right. Now,
consider another example:

In MATLAB, it becomes

>> 1/(2+3^2)+4/5*6/7

ans =

0.7766

or, if parentheses are missing,

>> 1/2+3^2+4/5*6/7

ans =

10.1857

16
So here what we get: two different results. Therefore, we want to emphasize the importance of
precedence rule in order to avoid ambiguity.

1.5.7 Controlling the appearance of floating point number


MATLAB by default displays only 4 decimals in the result of the calculations, for
example
−163.6667, as shown in above examples. However, MATLAB does numerical calculations in
double
precision, which is 15 digits. The command format controls how the results of computations are
displayed. Here are some examples of the different formats together with the resulting outputs.

>> format short

>> x=-163.6667

If we want to see all 15 digits, we use the command format long

>> format long

>> x= -1.636666666666667e+002

To return to the standard format, enter format short, or simply format.


There are several other formats. For more details, see the MATLAB documentation, or type help
format.

Note - Up to now, we have let MATLAB repeat everything that we enter at the prompt (>>).
Sometimes this is not quite useful, in particular when the output is pages en length. To prevent MATLAB
from echoing what we type, simply enter a semicolon (;) at the end of the command. For example,

>> x=-163.6667;

and then ask about the value of x by typing,

>> x

x =

-163.6667

1.5.8 Managing the workspace


The contents of the workspace persist between the executions of separate commands. There-
fore, it is possible for the results of one problem to have an effect on the next one. To avoid this
possibility, it is a good idea to issue a clear command at the start of each new independent calculation.

>> clear

The command clear or clear all removes all variables from the workspace. This frees up system
memory. In order to display a list of the variables currently in the memory, type

17
>> who

while, whos will give more details which include size, space allocation, and class of the variables.

1.5.9 Keeping track of your work session


It is possible to keep track of everything done during a MATLAB session with the diary command.

>> diary

or give a name to a created file,

>> diary FileName

where FileName could be any arbitrary name you choose.

The function diary is useful if you want to save a complete MATLAB session. They save all input
and output as they appear in the MATLAB window. When you want to stop the recording, enter diary off. If
you want to start recording again, enter diary on. The file that is created is a simple text file. It can be opened
by an editor or a word processing program and edited to remove extraneous material, or to add your comments.
You can use the function type to view the diary file or you can edit in a text editor or print. This command
is useful, for example in the process of preparing a homework or lab submission.

1.5.10 Entering multiple statements per line


It is possible to enter multiple statements per line. Use commas (,) or semicolons (;) to enter more than
one statement at once. Commas (,) allow multiple statements per line without suppressing output.

>> a=7; b=cos(a), c=cosh(a)

b =

0.6570

c =

548.3170

1.5.11 Miscellaneous commands


Here are few additional useful commands:

• To clear the Command Window, type clc


• To abort a MATLAB computation, type ctrl-c
• To continue a line, type . . .

18
1.5.12 Getting help
To view the online documentation, select MATLAB Help from Help menu or MATLAB Help
directly in the Command Window. The preferred method is to use the Help Browser. The Help Browser can
be started by selecting the ? icon from the desktop toolbar. On the other hand, information about any command
is available by typing

>> help Command

Another way to get help is to use the lookfor command. The lookfor command differs from the
help command. The help command searches for an exact function name match, while the lookfor
command searches the quick summary information in each function for a match. For example, suppose
that we were looking for a function to take the inverse of a matrix. Since MATLAB does not have a
function named inverse, the command help inverse will produce nothing. On the other hand, the
command lookfor inverse will produce detailed information, which includes the function of interest, inv.

>> lookfor inverse

Note - At this particular time of our study, it is important to emphasize one main point. Because
MATLAB is a huge program; it is impossible to cover all the details of each function one by one. However,
we will give you information how to get help. Here are some examples:

Use on-line help to request info on a specific function

>> help sqrt

In the current version (MATLAB version 7), the doc function opens the on-line version of
the help manual. This is very helpful for more complex commands.

>> doc plot

Use lookfor to find functions by keywords. The general form is

>> lookfor FunctionName

1.6 Exercises

19
2 Chapter 2

2.1 Mathematical functions


MATLAB offers many predefined mathematical functions for technical computing which contains a
large set of mathematical functions.

Typing help elfun and help specfun calls up full lists of elementary and specialfunctions
respectively.

There is a long list of mathematical functions that are built into MATLAB. These functions are
called built-ins. Many standard mathematical functions, such as sin(x), cos(x), tan(x), ex, ln(x), are
evaluated by the functions sin, cos, tan, exp, and log respectively in MATLAB.

Table 3 lists some commonly used functions, where variables x and y can be numbers, vectors, or
matrices.

Table 3: Elementary
functions.

20
In addition to the elementary functions, MATLAB includes a number of predefined constant
values. A list of the most common values is given in Table 4.

Table 4: Predefined constant


values

2.1.1 Examples

We illustrate here some typical examples which related to the elementary functions previously
defined.

As a first example, the value of the expression y = e−a sin(x) + 10√y, for a = 5, x = 2, and y = 8
is computed by

>> a = 5; x = 2; y = 8;

>> y = exp(-a)*sin(x)+10*sqrt(y)

y =

28.2904

The subsequent examples are

>> log(142)

ans =

4.9558

>> log10(142)

ans =

2.1523

Note the difference between the natural logarithm log(x) and the decimal logarithm (base 10)
log10(x).
21
To calculate sin(π/4) and e10 , we enter the following commands in MATLAB,

>> sin(pi/4)

ans =

0.7071

>> exp(10)

ans =

2.2026e+004

Notes:

• Only use built-in functions on the right hand side of an expression. Reassigning the value to a
built-in function can create problems.
• There are some exceptions. For example, i and j are pre-assigned to . However one or
both of i or j are often used as loop indices.
• To avoid any possible confusion, it is suggested to use instead ii or jj as loop indices.

2.2 Basic plotting

2.2.1 Overview
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results of computation
is possible with very few commands. You are highly encouraged to plot mathematical functions and
results of analysis as often as possible. Trying to understand mathematical equations with graphics is an
enjoyable and very efficient way of learning math- ematics. Being able to plot mathematical functions and
data freely is the most important step, and this section is written to assist you to do just that.

2.2.2 Creating simple plots


The basic MATLAB graphing procedure, for example in 2D, is to take a vector of x- coordinates, x
= (x1, . . . , xN ), and a vector of y-coordinates, y = (y1, . . . , yN ), locate the points (xi, yi), with i = 1, 2, . . . ,
n and then join them by straight lines. You need to prepare x and y in an identical array form; namely, x and
y are both row arrays or column arrays of the same length.

The MATLAB command to plot a graph is plot(x,y). The vectors x = (1, 2, 3, 4, 5, 6) and y = (3, −1,
2,
4, 5, 1) produce the picture shown in Figure 2.1.

>> x = [1 2 3 4 5 6];

>> y = [3 -1 2 4 5 1];

>> plot(x,y)

22
Note: The plot functions 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 we
specify two vectors, as mentioned above, plot(x,y) produces a graph of y versus x.

For example, to plot the function sin (x) on the interval [0, 2π], we first create a vector of x values
ranging from 0 to 2π, then compute the sine of these values, and finally plot the result:

Figure 12: Plot for the vectors


x and y

>> x = 0:pi/100:2*pi;

>> y = sin(x);

>>

plot(x,y)

Notes:

• 0:pi/100:2*pi yields a vector that


– starts at 0,
– takes steps (or increments) of π/100,
– stops when 2π is reached.
• If you omit the increment, MATLAB automatically increments by 1.

2.2.3 Adding titles, axis labels, and annotations


MATLAB enables you to add axis labels and titles. For example, using the graph from the previous
example, add an x- and y-axis labels.

Now label the axes and add a title. The character \pi creates the symbol π. An example of 2D plot
is shown in Figure 2.2.

23
Figure 2.2: Plot of the Sine
function

>> xlabel(’x = 0:2\pi’)

>> ylabel(’Sine of x’)

>> title(’Plot of the Sine function’)

The color of a single curve is, by default, blue, but other colors are possible. The desired color is
indicated by a third argument. For example, red is selected by plot(x,y,’r’). Note the single quotes, ’ ’, around
r.

2.2.4 Multiple data sets in one plot


Multiple (x, y) pairs arguments create multiple graphs with a single call to plot. For example, these
statements plot three related functions of x: y1 = 2cos(x), y2 = cos(x), and y3 = 0.5*cos(x), in the interval
0 ≤ x ≤ 2π.

>> x = 0:pi/100:2*pi;

>> y1 = 2*cos(x);

>> y2 = cos(x);

>> y3 = 0.5*cos(x);

>> plot(x,y1,'--',x,y2,'-',x,y3,':')

>> xlabel('0 \leq x \leq 2\pi')

>> ylabel('Cosine functions')


24
>> legend('2*cos(x)','cos(x)','0.5*cos(x)')

>> title('Typical example of multiple plots')

>> axis([0 2*pi -3 3])

The result of multiple data sets in one graph plot is shown in Figure 13.

Figure 13: Typical example of


multiple plots.
By default, MATLAB uses line style and color to distinguish the data sets plotted in the graph.
However, you can change the appearance of these graphic components or add annotations to the graph to help
explain your data for presentation.

2.2.5 Specifying line styles and colors


It is possible to specify line styles, colors, and markers (e.g., circles, plus signs, . . . ) using the plot
command: plot(x,y,’style_color_marker’), where style_color_marker is a triplet of values from Table 5.

To find additional information, type help plot or doc plot.

Table 5: Attributes
for plot

Symbol Color Symbol Line Style Symbol Marker

25
k Black − Solid + Plus sign
r Red − Dashed o Circle
b Blue :− Dotted ∗ Asterisk
g Green −. Dash-dot . Point
c Cyan none No line × Cross
m Magenta s Square
y Yellow d Diamond

Specifying the Color and Size of Markers You can also specify other line characteristics
using graphics properties (see line for a description of these properties):

LineWidth —Specifies the width (in points) of the line.

MarkerEdgeColor —Specifies the color of the marker or the edge color for filled markers
(circle,square, diamond, pentagram, hexagram, and the four triangles).

MarkerFaceColor —Specifies the color of the face of filled markers.

MarkerSize —Specifies the size of the marker in units of points.

For example, these statements, produce the graph of

x = -pi:pi/10:pi;

y = tan(sin(x)) - sin(tan(x));

plot(x,y,'--rs','LineWidth',2,...

'MarkerEdgeColor','k',...

'MarkerFaceColor','g',...

'MarkerSize',10)

26
Figure 14: the graph of the precedent
example.

2.2.6 Copy/Paste Figures


Figures can be pasted into other apps (word, ppt, etc)

Edit copy options figure copy template Change font sizes, line properties; presets for word
and ppt.

Edit copy figure to copy figure.

Paste into document of interest.

Figure 15: Copy/Paste


Figures.

27
2.2.7 Saving Figures
Figures can be saved in many formats. The common ones are given the following figure.

Figure 16: Saving


figure.

2.3 Exercises

28
2.4 Animations
MATLAB provides two ways of generating moving, animated graphics:

Continually erase and then redraw the objects on the screen, making incremental changes
with each redraw.
Save a number of different pictures and then play them back as a movie.

2.4.1 Erase Mode Method


Using the EraseMode property is appropriate for long sequences of simple plots where the change
from frame to frame is minimal. Here is an example showing simulated Brownian motion. Specify a
number of points, such as

n = 20

and a temperature or velocity, such as s

= .02

The best values for these two parameters depend upon the speed of your particular computer.
Generate n random points with (x,y) coordinates between –1/2 +1/2.

x = rand(n,1)-0.5;

y = rand(n,1)-0.5;

Plot the points in a square with sides at -1 and +1. Save the handle for the vector of points and set its
EraseMode to xor. This tells the MATLAB graphics system not to redraw the entire plot when the coordinates
of one point are changed, but to restore the background color in the vicinity of the point using an “exclusive
or” operation.

h = plot(x,y,'.');

axis([-1 1 -1 1])

axis square

grid off

set(h,'EraseMode','xor','MarkerSize',18)

Now begin the animation. Here is an infinite while loop, which you can eventually exit by typing
Ctrl+c. Each time through the loop, add a small amount of normally distributed random noise to the
coordinates of the points.

Then, instead of creating an entirely new plot, simply change the XData and YData properties of
the original plot.

while 1

29
drawnow

x = x + s*randn(n,1);

y = y + s*randn(n,1);

set(h,'XData',x,'YData',y)

end

How long does it take for one of the points to get outside of the square? How long before all of the
points are outside the square?

Figure 17:
Animation.

2.4.2 Creating Movies


If you increase the number of points in the Brownian motion example to something like n = 300
and s = .02, the motion is no longer very fluid; it takes too much time to draw each time step. It becomes
more effective to save a predetermined number of frames as bitmaps and to play them back as a movie.

First, decide on the number of frames, say nframes = 50;

Next, set up the first plot as before, except using the default EraseMode (normal).

x = rand(n,1)-0.5;

y = rand(n,1)-0.5;

h = plot(x,y,'.');

set(h,'MarkerSize',18);

30
axis([-1 1 -1 1])

axis square

grid off

Generate the movie and use getframe to capture each frame.

for k = 1:nframes

x = x + s*randn(n,1);

y = y + s*randn(n,1);

set(h,'XData',x,'YData',y)

M(k) = getframe;

end

Finally, play the movie 30 times.

movie(M,30)

2.5 Working with Matrices

2.5.1 Introduction

Matrices are the basic elements of the MATLAB environment. A matrix is a two-dimensional array
consisting of m rows and n columns. Special cases are column vectors (n = 1) and row vectors (m = 1).

In this section we will illustrate how to apply different operations on matrices. The following topics
are discussed: vectors and matrices in MATLAB, the inverse of a matrix, determinants, and matrix
manipulation.

MATLAB supports two types of operations, known as matrix operations and array opera- tions.
Matrix operations will be discussed first.

2.5.2 Matrix generation


Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrix generation
and manipulation. Matrices can be generated in several ways.

2.5.2.1 Entering a vector


A vector is a special case of a matrix. The purpose of this section is to show how to create vectors and
matrices in MATLAB. As discussed earlier, an array of dimension 1 × n is called a row vector, whereas an
array of dimension m × 1 is called a column vector. The elements of vectors in MATLAB are enclosed by
square brackets and are separated by spaces or by commas. For example, to enter a row vector, v, type

31
>> v = [1 4 7 10 13]

v =

1 4 7 10 13

Column vectors are created in a similar way, however, semicolon (;) must separate the
components of a column vector,

>> w = [1;4;7;10;13]

w =

10

13

On the other hand, a row vector is converted to a column vector using the transpose operator. The
transpose operation is denoted by an apostrophe or a single quote (’).

>> w = v’

w =

10

13

Thus, v(1) is the first element of vector v, v(2) its second element, and so forth. Furthermore, to access
blocks of elements, we use MATLAB’s colon notation (:). For example, to access the first three elements of
v, we write,

>> v(1:3)

ans =

1 4 7

Or, all elements from the third through the last elements,

32
>> v(3,end)

ans =

7 10 13

where end signifies the last element in the vector. If v is a vector, writing

>> v(:)

produces a column vector, whereas writing

>> v(1:end)

produces a row vector.

2.5.2.2 Entering a
matrix

A matrix is an array of numbers. To type a matrix into MATLAB you must

• begin with a square bracket, [


• separate elements in a row with spaces or commas (,)
• use a semicolon (;) to separate rows
• end the matrix with another square bracket, ].

Here is a typical example. To enter a matrix A, such as,

type,

>> A = [1 2 3; 4 5 6; 7 8 9]

MATLAB then displays the 3 × 3 matrix as follows,

A =

1 2 3
4 5 6

7 8 9

Note that the use of semicolons (;) here is different from their use mentioned earlier to suppress
output or to write multiple commands in a single line.

33
Once we have entered the matrix, it is automatically stored and remembered in the Workspace.
We can refer to it simply as matrix A. We can then view a particular element in a matrix by specifying its
location. We write,

>> A(2,1)

ans =

A(2,1) is an element located in the second row and first column. Its value is 4.

2.5.2.3 Matrix indexing


We select elements in a matrix just as we did for vectors, but now we need two indices. The element
of row i and column j of the matrix A is denoted by A(i,j). Thus, A(i,j) in MATLAB refers to the element Aij
of matrix A. The first index is the row number and the second index is the column number. For example,
A(1,3) is an element of first row and third column. Here, A(1,3)=3.

Correcting any entry is easy through indexing. Here we substitute A(3,3)=9 by

A(3,3)=0. The result is

>> A(3,3) = 0

Single elements of a matrix are accessed as A(i,j), where i ≥ 1 and j ≥ 1. Zero or negative subscripts
are not supported in MATLAB.

2.5.2.4 Colon operator


The colon operator will prove very useful and understanding how it works is the key to efficient
and convenient usage of MATLAB. It occurs in several different forms.

Often we must deal with matrices or vectors that are too large to enter one ele- ment at a time. For
example, suppose we want to enter a vector x consisting of points (0, 0.1, 0.2, 0.3, · · · , 5). We can use the
command

>> x = 0:0.1:5;

The row vector has 51 elements.

2.5.2.5 Linear spacing


On the other hand, there is a command to generate linearly spaced vectors: linspace. It is similar
to the colon operator (:), but gives direct control over the number of points. For example,

y = linspace(a,b)

generates a row vector y of 100 points linearly spaced between and including a and b.

34
y = linspace(a,b,n)

generates a row vector y of n points linearly spaced between and including a and b. This is useful
when we want to divide an interval into a number of subintervals of the same length. For example,

>> theta = linspace(0,2*pi,101)

divides the interval [0, 2π] into 100 equal subintervals, then creating a vector of 101 elements.

2.5.2.6 Colon operator in a matrix


The colon operator can also be used to pick out a certain row or column. For example, the
statement A(m:n,k:l specifies rows m to n and column k to l. Subscript expressions refer to portions of a
matrix. For example,

>> A(2,:)

ans =

4 5 6

is the second row elements of A.

The colon operator can also be used to extract a sub-matrix from a matrix A.

>> A(:,2:3)

ans =

2 3

5 6

8 0

A(:,2:3) is a sub-matrix with the last two columns of A.

A row or a column of a matrix can be deleted by setting it to a null vector, [ ].

>> A(:,2)=[]

ans =

1 3

4 6

7 0

35
2.5.2.7 Creating a sub-matrix
To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the matrix A, do the
following

>> B = A([2 3],[1 2])

B =

4 5

7 8

To interchange rows 1 and 2 of A, use the vector of row indices together with the colon operator.

>> C = A([2 1 3],:)

C =

4 5 6

1 2 3

7 8 0

It is important to note that the colon operator (:) stands for all columns or all rows. To create a
vector version of matrix A, do the following

>> A(:)

ans =

The submatrix comprising the intersection of rows p to q and columns r to s is denoted by


A(p:q,r:s).

36
As a special case, a colon (:) as the row or column specifier covers all entries in that row or column;
thus

• A(:,j) is the jth column of A, while


• A(i,:) is the ith row, and
• A(end,:) picks out the last row of A.

The keyword end, used in A(end,:), denotes the last index in the specified dimension. Here are
some examples.

>> A

A=

1 2 3

4 5 6

7 8 9

>> A(2:3,2:3)

ans =

5 6

8 9

>> A(end:-1:1,end)

ans =

>> A([1 3],[2 3])

ans =

2 3

8 9

2.5.2.8 Deleting row or column


To delete a row or column of a matrix, use the empty vector operator, [ ].

>> A(3,:) = []

37
A =

1 2 3

4 5 6

Third row of matrix A is now deleted. To restore the third row, we use a technique for creating a
matrix

>> A = [A(1,:);A(2,:);[7 8 0]]

A=

1 2 3

4 5 6
7 8 9

Matrix A is now restored to its original form.

2.5.2.9 Dimension
To determine the dimensions of a matrix or vector, use the command size. For example,

>> size(A)

ans =

3 3

means 3 rows and 3 columns. Or more explicitly with,

>> [m,n]=size(A)

2.5.2.10 Continuation
If it is not possible to type the entire input on the same line, use consecutive periods, called an
ellipsis . . ., to signal continuation, then continue the input on the next line.

B = [4/5 7.23*tan(x) sqrt(6); ...


1/x^2 0 3/(x*log(x));
...
x-7 sqrt(3) x*sin(x)];

Note that blank spaces around +, −, = signs are optional, but they improve readability.

2.5.2.11 Transposing a matrix


The transpose operation is denoted by an apostrophe or a single quote (’). It flips a matrix about
its main diagonal and it turns a row vector into a column vector. Thus,

38
>> A’

ans =

1 4 7

2 5 8

3 6 0

By using linear algebra notation, the transpose of m × n real matrix A is the n × m matrix that
results from interchanging the rows and columns of A. The transpose matrix is denoted AT .

2.5.2.12 Concatenating matrices


Matrices can be made up of sub-matrices. Here is an example. First, let’s recall our previous matrix
A.

A =

1 2 3

4 5 6

7 8 9

The new matrix B will be,

>> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]] B =

1 2 3 10 20 30

4 5 6 40 50 60

7 8 9 70 80 90

-1 -2 -3 1 0 0

-4 -5 -6 0 1 0

-7 -8 -9 0 0 1

2.5.2.13 Matrix generators


MATLAB provides functions that generate elementary matrices. The matrix of zeros, the matrix of
ones, and the identity matrix are returned by the functions zeros, ones, and eye, respectively.
Table 6: Elementary
matrices.

eye(m,n) Returns an m-by-n matrix with 1 on the main diagonal


eye(n) Returns an n-by-n square identity matrix

39
zeros(m,n) Returns an m-by-n matrix of zeros
ones(m,n) Returns an m-by-n matrix of ones
diag(A) Extracts the diagonal of matrix A
rand(m,n) Returns an m-by-n matrix of random numbers
For a complete list of elementary matrices and matrix manipulations, type help elmat or doc
elmat. Here are some examples:

1. >> b=ones(3,1)
b =
1
1
1

Equivalently, we can define b as >> b=[1;1;1]

2. >> eye(3)

ans =

1 0 0

0 1 0

0 0 1

3. >> c=zeros(2,3)

c =

0 0 0
0 0 0

In addition, it is important to remember that the three elementary operations of ad- dition (+),
subtraction (−), and multiplication (*) apply also to matrices whenever the dimensions are compatible.

Two other important matrix generation functions are rand and randn, which generate matrices of
(pseudo-)random numbers using the same syntax as eye.

In addition, matrices can be constructed in a block form. With C defined by C = [1 2; 3 4], we may
create a matrix D as follows

>> D = [C zeros(2); ones(2) eye(2)]

D=

1 2 0 0

40
3 4 0 0

1 1 1 0

1 1 0 1

2.5.2.14 Special matrices


MATLAB provides a number of special matrices (see Table 2.5). These matrices have inter- esting
properties that make them useful for constructing examples and for testing algorithms. For more information,
see MATLAB documentation.

Table 7: Special
matrices

hilb Hilbert matrix


invhilb Inverse Hilbert
matrix magic Magic square
pascal Pascal matrix
toeplitz Toeplitz matrix
vander Vandermonde matrix
wilkinson Wilkinson’s eigenvalue test matrix

2.6 Exercises

41
3 Chapter 3: Array operations and Linear equations

3.1 Array operations

MATLAB has two different types of arithmetic operations: matrix arithmetic operations and array
arithmetic operations. We have seen matrix arithmetic operations in the previous lab. Now, we are
interested in array operations.

3.1.1 Matrix arithmetic operations


As we mentioned earlier, MATLAB allows arithmetic operations: +, −, ∗, and ˆ to be carried out
on matrices. Thus,

A+B or B+A is valid if A and B are of the same size


A*B is valid if A’s number of column equals B’s number of rows
A^2 is valid if A is square and equals A*A
α*A or A*α multiplies each element of A by α

3.1.2 Array arithmetic operations


On the other hand, array arithmetic operations or array operations for short, are done element-by-
element. The period character, ., distinguishes the array operations from the matrix operations. However, since
the matrix and array operations are the same for addition (+) and subtraction (−), the character pairs (.+) and
(.−) are not used. The list of array operators is shown below in Table 8Table 8. If A and B are two matrices
of the same size with elements A = [aij ] and B = [bij ], then the command
Table 8: Array
operators
.* Element-by-element multiplication
./ Element-by-element division
.^ Element-by-element exponentiation

>> C =
A.*B

produces another matrix C of the same size with elements cij = aij bij . For example, using the
same 3 × 3 matrices,

we have,

>> C = A.*B

42
10 40 90

160 250 360

490 640 810

To raise a scalar to a power, we use for example the command 10^2. If we want the operation to
be applied to each element of a matrix, we use .^2. For example, if we want to produce a new matrix
whose elements are the square of the elements of the matrix A, we enter

>>
A.^2
=
ans

1 4 9
16 25 36

49 64 81

The relations below summarize the above operations. To simplify, let’s consider two vectors U
and V with elements U = [ui] and V = [vj ].

U. ∗ V produces

U./V produces

U.ˆV produces [ ]

Table 9: Summary of matrix and array operations.

Operation Matrix Array


Addition + +
Subtraction − −
Multiplication * .*
Division / ./
Left division \ \
Exponentiation ^ .^

3.2 Solving linear equations


One of the problems encountered most frequently in scientific computation is the solution of systems
of simultaneous linear equations. With matrix notation, a system of simultaneous linear equations is written

Ax = b

where there are as many equations as unknown. A is a given square matrix of order n, b is a given
column vector of n components, and x is an unknown column vector of n components.

43
In linear algebra we learn that the solution to Ax = b can be written as x = A−1b, where A−1 is
the inverse of A.

For example, consider the following system of linear equations

The coefficient matrix A is

With matrix notation, a system of simultaneous linear equations is written

Ax = b

This equation can be solved for x using linear algebra. The result is x =

A−1b. There are typically two ways to solve for x in MATLAB:

1. The first one is to use the matrix inverse, inv.

>> A = [1 2 3; 4 5 6; 7 8 0];

>> b = [1; 1; 1];

>> x = inv(A)*b

x =

-1.0000

1.0000

-0.0000

2. The second one is to use the backslash (\)operator. The numerical algorithm behind this
operator is computationally efficient. This is a numerically reliable way of solving system of
linear
equations by using a well-known process of Gaussian elimination.

>> A = [1 2 3; 4 5 6; 7 8 0];

>> b = [1; 1; 1];

>> x = A\b

x =

-1.0000
44
1.0000

-0.0000

This problem is at the heart of many problems in scientific computation. Hence it is important that
we know how to solve this type of problem efficiently.

Now, we know how to solve a system of linear equations. In addition to this, we will see some
additional details which relate to this particular topic.

3.2.1 Matrix inverse


Let’s consider the same matrix A.

Calculating the inverse of A manually is probably not a pleasant work. Here the hand- calculation
of A−1 gives as a final result:

In MATLAB, however, it becomes as simple as the following commands:

>> A = [1 2 3; 4 5 6; 7 8 0];

>> inv(A)

ans =

-1.7778 0.8889 -0.1111

1.5556 -0.7778 0.2222

-0.1111 0.2222 -0.1111

which is similar to:

and the determinant of A is

>> det(A)

ans =

27

49
For further details on applied numerical linear algebra, see [10] and [11].

3.2.2 Matrix functions


MATLAB provides many matrix functions for various matrix/vector manipulations; see Table 10
for some of these functions. Use the online help of MATLAB to find how to use these functions.

Table 10: Matrix


functions

det Determinant
diag Diagonal matrices and diagonals of a
matrix eig Eigenvalues and eigenvectors
inv Matrix inverse
norm Matrix and vector norms
rank Number of linearly independent rows or columns

3.3 Exercises

50
4 Chapter 4: Introduction to programming in
MATLAB

4.1 Introduction
So far in these lab sessions, all the commands were executed in the Command Window. The problem
is that the commands entered in the Command Window cannot be saved and executed again for several times.
Therefore, a different way of executing repeatedly commands with MATLAB is:

1. to create a file with a list of commands,


2. save the file, and
3. run the file.

If needed, corrections or changes can be made to the commands in the file. The files that are used for
this purpose are called script files or scripts for short.

This section covers the following topics:

• M-File Scripts
• M-File Functions

4.2 M-File Scripts


A script file is an external file that contains a sequence of MATLAB statements. Script files have a
filename extension .m and are often called M-files. M-files can be scripts that simply execute a series of
MATLAB statements, or they can be functions that can accept arguments and can produce one or more outputs.

4.2.1 Examples
Here are two simple scripts.

Example 1

Consider the system of equations:

Find the solution x to the system of equations.

Solution:

• Use the MATLAB editor to create a file: File → New → M-file.


• Enter the following statements in the file:

51
A = [1 2 3; 3 3 4; 2 3 3];

b = [1; 1; 2];

x = A\b

• Save the file, for example, example1.m.


• Run the file, in the command line, by typing:

>> example1

x =

-0.5000

1.5000

-0.5000

When execution completes, the variables (A, b, and x) remain in the workspace. To see a listing of
them, enter whos at the command prompt.

Note: The MATLAB editor is both a text editor specialized for creating M-files and a graphical
MATLAB debugger. The MATLAB editor has numerous menus for tasks such as saving, viewing,
and debugging. Because it performs some simple checks and also uses color to differentiate between various
elements of codes, this text editor is recommended as the tool of choice for writing and editing M-files.

There is another way to open the editor:

>> edit

or

>> edit filename.m

to open filename.m.

Example 2

Plot the following cosine functions, y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 ∗ cos(x), in the interval 0
≤ x ≤ 2π. This example has been presented in previous Chapter. Here we put the commands in a file.

Create a file, say example2.m, which contains the following commands:

x = 0:pi/100:2*pi;

y1 = 2*cos(x);

y2 = cos(x);

y3 = 0.5*cos(x);

52
plot(x,y1,’--’,x,y2,’-’,x,y3,’:’)

xlabel(’0 \leq x \leq 2\pi’)

ylabel(’Cosine functions’)

legend(’2*cos(x)’,’cos(x)’,’0.5*cos(x)’)

title(’Typical example of multiple plots’)

axis([0 2*pi -3 3])

Run the file by typing example2 in the Command Window.

4.2.2 Script side-effects


All variables created in a script file are added to the workspace. This may have undesirable effects,
because:

• Variables already existing in the workspace may be overwritten.


• The execution of the script can be affected by the state variables in the workspace.

As a result, because scripts have some undesirable side-effects, it is better to code any
complicated applications using rather function M-file.

4.3 M-File functions


As mentioned earlier, functions are programs (or routines ) that accept input arguments and
return output arguments. Each M-file function (or function or M-file for short) has its own area of workspace,
separated from the MATLAB base workspace.

4.3.1 Anatomy of a M-File function


This simple function shows the basic parts of an M-file.

function f = factorial(n) (1)

% FACTORIAL(N) returns the factorial of N. (2)

% Compute a factorial value. (3)

f = prod(1:n); (4)

The first line of a function M-file starts with the keyword function. It gives the function name and
order of arguments. In the case of function factorial, there are up to one output argument and one input
argument. Table 11 summarizes the M-file function.

As an example, for n = 5, the result is,

>> f = factorial(5)

53
f=

120

Table 11: Anatomy of a M-File


function

Part no. M-file element Description


(1) Function Define the function name, and the number and order of input and
definition line output arguments

(2) H1 line A one line summary description of the program, displayed when
you request Help
(3) Help text A more detailed description of the program
(4) Function body Program code that performs the actual computations

Both functions and scripts can have all of these parts, except for the function definition line which
applies to function only.

In addition, it is important to note that function name must begin with a letter, and must be no longer
than the maximum of 63 characters. Furthermore, the name of the text file that you save will consist of
the function name with the extension .m. Thus, the above example file would be factorial.m.

Table 12 summarizes the differences between scripts and functions.

Table 12: Difference between scripts and functions.

Scripts Functions
- Do not accept inputarguments or - Can accept input arguments and return
return output arguments. output arguments.
- Store variables in a workspace that is - Store variables in a workspace internal to
shared with other scripts the function.
- - Are useful for automating a series of - Are useful for extending the MATLAB
commands language for your application

4.3.2 Input and output arguments


As mentioned above, the input arguments are listed inside parentheses following the function name.
The output arguments are listed inside the brackets on the left side. They are used to transfer the output from
the function file. The general form looks like this

function [outputs] = function_name(inputs)

Function file can have none, one, or several output arguments. Table 13 illustrates some possible
combinations of input and output arguments.

Table 13: Example of input and output arguments.

function C=FtoC(F) One input argument and one output


argument function area=TrapArea(a,b,h) Three inputs and one output
function [h,d]=motion(v,angle) Two inputs and two outputs
54
4.4 Input/Output Commands
MATLAB has commands for inputting information in the command window and outputting data.
Examples of input/output commands are echo, input, pause, keyboard, break, error, display, format, and
fprintf. Brief descriptions of these commands are shown in Table 14.

Table 14: Some Input/output


Commands

COMMAND DESCRIPTION
break exits while or for
loops disp displays text or
matrix
echo displays m-files during
execution error displays error
messages
format switches output display to a particular format
fprintf displays text and matrices and specifies format for printing values
input allows user input
keyboard invokes the keyboard as an m-file
pause causes an m-file to stop executing. Press ing any key cause resumption of program execution.
Break

The break command may be used to terminate the execution of for and while loops. If the break
command exits in an innermost part of a nested loop, the break command will exit from that loop only.
The break command is useful in exiting a loop when an error condition is detected.

Disp

The disp command displays a matrix without printing its name. It can also be used to display a
text string. The general form of the disp command is

disp(x)

disp(‘text string’)

disp(x) will display the matrix x. Another way of displaying matrix x is to type its name. This is not
always desirable since the display will start with a leading “x = ”. Disp(‘text string’) will display the text
string in quotes. For example, the MATLAB statement

disp(‘3-by-3 identity matrix’)

will result in

3-by-3 identity matrix

and

disp(eye(3,3))

will result in

1 0 0
55
0 1 0

0 0 1

Echo

The echo command can be used for debugging purposes. The echo command allows commands to
be viewed as they execute. The echo can be enabled or disabled.

echo on - enables the echoing of commands

echo off - disables the echoing of commands

echo - by itself toggles the echo state

Erro
r

The error command causes an error return from the m-files to the keyboard and displays a user
written message. The general form of the command is

error(‘message for display’)

Consider the following MATLAB


statements:

x = input(‘Enter age of student’);

if x < 0

error(‘wrong age was entered, try again’)

end

x = input(‘Enter age of student’)

For the above MATLAB statements, if the age is less than zero, the error message ‘wrong age was
entered, try again’ will be displayed and the user will again be prompted for the correct age.

Format

The format controls the format of an output. Table 15 shows some formats available in MATLAB.

Table 15: Format


Displays.

COMMAND MEANING
format short 5 significant decimal digits
format long 15 significant digits
format short e scientific notation with 5 significant digits
format long e scientific notation with 15 significant digits
format hex hexadecimal
format + + printed if value is positive, - if negative; space is skipped if value is zero

56
By default, MATLAB displays numbers in “short” format (5 significant dig- its). Format compact
suppresses line-feeds that appear between matrix dis- plays, thus allowing more lines of information to be
seen on the screen. Format loose reverts to the less compact display. Format compact and format loose do
not affect the numeric format.

fprintf

The fprintf can be used to print both text and matrix values. The format for printing the matrix
can be specified, and line feed can also be specified. The general form of this command is

fprintf(‘text with format specification’, matrices)

For example, the following statements

cap = 1.0e-06;

fprintf('The value of capacitance is %7.3e Farads\n', cap)

when executed will yield the output

The value of capacitance is 1.000e-006 Farads

The format specifier %7.3e is used to show where the matrix value should be printed in the text.
7.3e indicates that the capacitance value should be printed with an exponential notation of 7 digits,
three of which should be decimal digits. Other format specifiers are

%f - floating point

%g - signed decimal number in either %e or %f format, whichever is shorter

The text with format specification should end with \n to indicate the end of line. However, we can
also use \n to get line feeds as represented by the fol- lowing example:

r1 = 1500;

fprintf('resistance is \n%f Ohms \n', r1)

the output is

resistance is

1500.000000 Ohms

Input

The input command displays a user-written text string on the screen, waits for an input from the
keyboard, and assigns the number entered on the keyboard as the value of a variable. For example, if one types
the command

57
r = input(‘Please enter the four resistor values’);

when the above command is executed, the text string ‘Please, enter the four resistor values’ will
be displayed on the terminal screen. The user can then type an expression such as

[10 15 30 25];

The variable r will be assigned a vector [10 15 30 25]. If the user strikes the return key, without
entering an input, an empty matrix will be assigned to r.

To return a string typed by a user as a text variable, the input command may take the form

x = input(‘Enter string for prompt’, ’s’)

For example, the command

x = input(‘What is the title of your graph’, ’s’)

when executed, will echo on the screen, ‘What is the title of your graph.’ The user can enter a string
such as ‘Voltage (mV) versus Current (mA).’

Keyboard

The keyboard command invokes the keyboard as an m-file. When the word keyboard is placed in
an m-file, execution of the m-file stops when the word keyboard is encountered. MATLAB commands can
then be entered. The keyboard mode is terminated by typing the word, “return” and pressing the return key.
The keyboard command may be used to examine or change a vari- able or may be used as a tool for debugging
m-files.

Pause

The pause command stops the execution of m-files. The execution of the m- file resumes upon
pressing any key. The general forms of the pause command are

pause pause(n)

Pause stops the execution of m-files until a key is pressed. Pause(n) stops the execution of m-files
for n seconds before continuing. The pause command can be used to stop m-files temporarily when
plotting commands are encountered during program execution. If pause is not used, the graphics are
momentarily visible.

4.5 Exercises

© 1999 CRC Press LLC 58


5 Chapter 5: Control flow and operators

5.1 Introduction
MATLAB is also a programming language. Like other computer programming languages, MATLAB
has some decision making structures for control of command execution. These decision making or control
flow structures include for loops, while loops, and if-else-end constructions. Control flow structures are often
used in script M-files and function M-files.

By creating a file with the extension .m, we can easily write and run programs. We do not need to
compile the program since MATLAB is an interpretative (not compiled) language. MATLAB has thousand
of functions, and you can add your own using m-files.

MATLAB provides several tools that can be used to control the flow of a program (script or
function ). In a simple program as shown in the previous Chapter, the commands are executed one after the
other. Here we introduce the flow control structure that make possible to skip commands or to execute
specific group of commands.

5.2 Control flow


MATLAB has four control flow structures: the if statement, the for loop, the while loop, and the switch
statement.

5.2.1 The ‘‘if...end’’structure


MATLAB supports the variants of “if” construct.

• if ... end
• if ... else ... end
• if ... elseif ... else ... end

The simplest form of the if statement is

if expression

statements

end

Here are some examples based on the familiar quadratic formula.

Example 1

discr = b*b - 4*a*c;

if discr < 0

disp(’Warning: discriminant is negative, roots are imaginary’);

59
end

Example 2

discr = b*b - 4*a*c;

if discr < 0

disp(’Warning: discriminant is negative, roots are imaginary’);

else

disp(’Roots are real, but may be repeated’)

end

Example 3

discr = b*b - 4*a*c;

if discr < 0

disp(’Warning: discriminant is negative, roots are imaginary’);

elseif discr == 0

disp(’Discriminant is zero, roots are repeated’)

else

disp(’Roots are real’)

end

It should be noted that:

• elseif has no space between else and if (one word)


• no semicolon (;) is needed at the end of lines containing if, else, end
• indentation of if block is not required, but facilitate the reading.
• the end statement is required

5.2.2 Relational and logical operators


A relational operator compares two numbers by determining whether a comparison is true or
false. Relational operators are shown in Table 5.1.

Table 16: Relational and logical


operators

Operator Description
> Greater than
< Less than

60
>= Greater than or equal to
<= Less than or equal to
== Equal to
∼= Not equal to
& AND operator
| OR operator
∼ NOT operator
Note that the “equal to” relational operator consists of two equal signs (==) (with no space
between them), since = is reserved for the assignment operator.

5.2.3 The ‘‘for...end’’loop


In the for ... end loop, the execution of a command is repeated at a fixed and predetermined
number of times. The syntax is

for variable = expression

statements

end

Usually, expression is a vector of the form i:s:j. A simple example of for loop is

for ii=1:5

x=ii*ii

end

It is a good idea to indent the loops for readability, especially when they are nested. Note that
MATLAB editor does it automatically.

Multiple for loops can be nested, in which case indentation helps to improve the readability. The
following statements form the 5-by-5 symmetric matrix A with (i, j) element i/j for j ≥ i:

n = 5; A = eye(n);

for j=2:n

for i=1:j-1

A(i,j)=i/j; A(j,i)=i/j;

end

end

61
5.2.4 The ‘‘while...end’’ loop
This loop is used when the number of passes is not specified. The looping continues until a stated
condition is satisfied. The while loop has the form:

while expression

statements

end

The statements are executed as long as expression is true.

x=1

while x <= 10

x = 3*x

end

It is important to note that if the condition inside the looping is not well defined, the looping will
continue indefinitely. If this happens, we can stop the execution by pressing Ctrl-C.

5.2.5 Other flow structures


• The break statement. A while loop can be terminated with the break statement, which passes
control to the first statement after the corresponding end. The break statement can also be used to
exit a for loop.
• The continue statement can also be used to exit a for loop to pass immediately to the next
iteration of the loop, skipping the remaining statements in the loop.
• Other control statements include return, continue, switch, etc. For more detail about these
commands, consul MATLAB documentation.

5.2.6 Operator precedence


We can build expressions that use any combination of arithmetic, relational, and logical operators.
Precedence rules determine the order in which MATLAB evaluates an expression. We have already seen
this in the “Tutorial Lessons”.

Here we add other operators in the list. The precedence rules for MATLAB are shown in this list
(Table 5.2), ordered from highest (1) to lowest (9) precedence level. Operators are evaluated from left to right.

Table 5.2: Operator precedence

Precedence Operator
1 Parentheses ()
2 Transpose (. ‘ ), power (.ˆ), matrix power (ˆ)

62
3 Unary plus (+), unary minus (−), logical negation (∼)
4 Multiplication (. ∗), right division (. /), left division (.\), matrix multiplication (∗),
matrix right division (/), matrix left division (\)
5 Addition (+), subtraction (−)
6 Colon operator (:)
7 Less than (<), less than or equal to (≤), greater (>),
greater than or equal to (≥), equal to (==), not equal to (∼=)
8 Element-wise AND, (&)
9 Element-wise OR, (|)

5.3 Saving output to a file


In addition to displaying output on the screen, the command fprintf can be used for writing the
output to a file. The saved data can subsequently be used by MATLAB or other softwares.

To save the results of some computation to a file in a text format requires the following steps:

1. Open a file using fopen


2. Write the output using fprintf
3. Close the file using fclose

Here is an example (script) of its use.

% write some variable length strings to a file

op = fopen(’weekdays.txt’,’wt’);

fprintf(op,’Sunday\nMonday\nTuesday\nWednesday\n’);

fprintf(op,’Thursday\nFriday\nSaturday\n’);

fclose(op);

This file (weekdays.txt) can be opened with any program that can read .txt file.

5.4 Exercises

63
6 Chapter 6: Debugging M-files

6.1 Introduction
This section introduces general techniques for finding errors in M-files. Debugging is the process
by which you isolate and fix errors in your program or code.

Debugging helps to correct two kind of errors:

• Syntax errors - For example omitting a parenthesis or misspelling a function name.


• Run-time errors - Run-time errors are usually apparent and difficult to track down. They produce
unexpected results.

6.2 Debugging process


We can debug the M-files using the Editor/Debugger as well as using debugging functions from the
Command Window. The debugging process consists of

• Preparing for debugging


• Setting breakpoints
• Running an M-file with breakpoints
• Stepping through an M-file
• Examining values
• Correcting problems
• Ending debugging

6.2.1 Preparing for debugging


Here we use the Editor/Debugger for debugging. Do the following to prepare for debugging:

• Open the file


• Save changes
• Be sure the file you run and any files it calls are in the directories that are on the search path.

6.2.2 Setting breakpoints


Set breakpoints to pause execution of the function, so we can examine where the problem might
be. There are three basic types of breakpoints:

• A standard breakpoint, which stops at a specified line.


• A conditional breakpoint, which stops at a specified line and under specified conditions.
• An error breakpoint that stops when it produces the specified type of warning, error,
• NaN, or infinite value.

You cannot set breakpoints while MATLAB is busy, for example, running an M-file.

64
6.2.3 Running with breakpoints
After setting breakpoints, run the M-file from the Editor/Debugger or from the Command

Window. Running the M-file results in the following:

• The prompt in the Command Window changes to


K>>
• indicating that MATLAB is in debug mode.
• The program pauses at the first breakpoint. This means that line will be executed when you
continue. The pause is indicated by the green arrow.
• In breakpoint, we can examine variable, step through programs, and run other calling functions.

6.2.4 Examining values


While the program is paused, we can view the value of any variable currently in the workspace.
Examine values when we want to see whether a line of code has produced the expected result or not. If the
result is as expected, step to the next line, and continue running. If the result is not as expected, then that line,
or the previous line, contains an error. When we run a program, the current workspace is shown in the Stack
field. Use who or whos to list the variables in the current workspace.

Viewing values as datatips

First, we position the cursor to the left of a variable on that line. Its current value appears. This is
called a datatip, which is like a tooltip for data. If you have trouble getting the datatip to appear, click in
the line and then move the cursor next to the variable.

6.2.5 Correcting and ending debugging


While debugging, we can change the value of a variable to see if the new value produces expected
results. While the program is paused, assign a new value to the variable in the Com- mand Window, Workspace
browser, or Array Editor. Then continue running and stepping through the program.

6.2.6 Ending debugging


After identifying a problem, end the debugging session. It is best to quit debug mode before
editing an M-file. Otherwise, you can get unexpected results when you run the file. To end debugging,
select Exit Debug Mode from the Debug menu.

6.2.7 Correcting an M-file


To correct errors in an M-file,

• Quit debugging
• Do not make changes to an M-file while MATLAB is in debug mode
• Make changes to the M-file
• Save the M-file

65
• Clear breakpoints
• Run the M-file again to be sure it produces the expected results.

For details on debugging process, see MATLAB documentation.

66
7 Appendix A: Summary of commands

Table 17: Arithmetic operators and special


characters

Character Description
+ Addition
− Subtraction
∗ Multiplication (scalar and array)
/ Division (right)
ˆ Power or exponentiation
: Colon; creates vectors with equally spaced elements
; Semi-colon; suppresses display; ends row in array
, Comma; separates array subscripts
... Continuation of lines
% Percent; denotes a comment; specifies output format
‘ Single quote; creates string; specifies matrix transpose
= Assignment operator
() Parentheses; encloses elements of arrays and input arguments
[] Brackets; encloses matrix elements and output arguments
Table 18: Array
operators

Character Description
.∗ Array multiplication
./ Array (right) division
.^ Array power
.\ Array (left) division
,’ Array (nonconjugated) transpose

Table 19: Relational and logical operators

67
Table 20: Managing workspace and file commands

Command Description
cd Change current directory
clc Clear the Command Window
clear (all) Removes all variables from the workspace
clear x Remove x from the
workspace copyfile Copy file or
directory
delete Delete files
Dir Display directory listing
exist Check if variables or functions are defined
Help Display help for MATLAB functions
lookfor Search for specified word in all help
entries mkdir Make new directory
movefile Move file or directory
pwd Identify current
directory rmdir Remove
directory
type Display contents of file
what List MATLAB files in current
directory which Locate functions and files
who Display variables currently in the workspace
whos Display information on variables in the workspace
Table 21: Predefined variables and math
constants

Table 22: Elementary matrices


and arrays

68
Table 23: Arrays and Matrices: Basic
information

Table A.8: Arrays and Matrices: operations and


manipulation

Table 24: Arrays and Matrices: matrix analysis and


linear equations.

Command Description
cond Condition number with respect to inversion
det Determinant
inv Matrix inverse
linsolve Solve linear system of equations
lu LU factorization
norm Matrix or vector norm
null Null space
orth Orthogonalization
rank Matrix rank

69
rref Reduced row echelon form
trace Sum of diagonal element

70

You might also like