You are on page 1of 30

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S.

Rahal

Introduction to MATLAB
Dr. Salah M. Rahal

22/8/1435H
1

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

What is MATLAB ?
MATLAB stands for MATrix LABoratory and the software is built up around
vectors and matrices that has evolved over a period of years.
It is a high-level programming language. It is an interpreted language - the
source code is not compiled but interpreted on the fly.
It is one of the easiest programming languages for writing mathematical
programs.
MATLAB is also a great tool for solving algebraic and differential equations
and for numerical integration.
MATLAB has powerful graphic tools and can produce nice pictures in both 2D
and 3D.
MATLAB also has some tool boxes useful for signal processing, image
processing, optimization, etc.
It is developed by The Mathworks, Inc.
(http://www.mathworks.com), where comprehensive documentation is
available.
The language, tools, and built-in math functions enable you to explore multiple
approaches and to reach a solution faster than with spreadsheets or traditional
programming languages, such as C/C++ or Java.
Key Features
- High-level language for numerical computation, visualization, and
application development.
- Interactive environment for iterative exploration, design, and problem
solving.
- Mathematical functions for linear algebra, statistics, Fourier analysis,
filtering, optimization, numerical integration, and solving ordinary
differential equations.
- Built-in graphics for visualizing data and tools for creating custom plots.
- Development tools for improving code quality and maintainability and
maximizing performance.
- Tools for building applications with custom graphical interfaces.
- Functions for integrating MATLAB based algorithms with external
applications and languages such as C/C++ , Java, .NET, and Microsoft
Excel.
Typical uses of MATLAB include: Math and computation, Algorithm
development, Modeling, simulation, and prototyping, Data analysis,
exploration, and visualization, Scientific and engineering graphics, Application
development, including GUI building.
Toolboxes
- a family of application-specific solutions. They are
comprehensive collections of MATLAB functions (M-files*) that extend the
2

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

MATLAB environment to solve particular classes of problems. They allow


you to learn and apply specialized technology.
Areas in which toolboxes are available include: Signal processing, Control
systems, Systems Identification, Simulation, Optimization, Neural networks,
Fuzzy logic, Wavelets, and many others.
MATLAB System
The MATLAB system consists of five main parts:
- Development Environment.
- The MATLAB Mathematical Function Library.
- The MATLAB Language.
- Handle Graphics.
- The MATLAB Application Program Interface (API).
Development Environment
This is the set of tools and facilities that help you use MATLAB functions and
files. Many of these tools are graphical user interfaces. MATLAB comprises
tools for:
- Data analysis and visualization.
- Numeric and symbolic computation.
- Engineering and scientific graphics.
- Modeling, simulation, and prototyping.
- Programming , application development, and GUI design.
- Converting MATLAB programs automatically to standalone C and C++
code.
MATLAB Language
It is a flexible interactive high-level matrix/ array language with control flow
statements, functions, data structures* input/output, and object-oriented
programming features. It allows engineers and scientists express their technical
ideas in a simple way.
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 matrices , Bessel functions, and fast Fourier transforms.
Handle Graphics
MATLAB has extensive facilities for displaying vectors and matrices as
graphs, as well as annotating and printing these graphs. It includes: High-level
commands for two-dimensional and three- dimensional data visualization,
image processing, animation and presentation graphics.
3

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

MATLAB Application Program Interface (API)


This is a library that allows you to write C/C++ and Fortran programs that
interact with MATLAB. It includes facilities for calling routines from
MATLAB (dynamic linking), calling MATLAB as a computational engine,
and for reading and writing MAT-files.
Revision History
December 1996
May 1997
September 1998
September 2000
June 2001
July 2002
August 2002
June 2004
October 2004
March 2005
June 2005
September 2005
March 2006
September 2006
March 2007
September 2007
March 2008
October 2008
March 2009
September 2009
March 2010
September 2010
April 2011
September 2011
March 2012
September 2012
March 2013
September 2013
March 2014

First printing
Second printing
Third printing
Fourth printing
Online only
Online only
Fifth printing
S-th printing
Online only
Online only
S-th printing
Online only
Online only
E-th printing
9-th printing
10-th printing
11-th printing
12 -th printing
13-th printing
14-th printing
15-th printing
16-th printing
Online only
17-th printing
18-th printing
19-th printing
20-th printing
21-th printing
22-th printing

*R- Release.

MATLAB 5
MATLAB 5.1
MATLAB 5.3
MATLAB 6 (R* 12)
MATLAB6.1 (R 12.1)
MATLAB 6.5 (R 13)
MATLAB 6.5
MATLAB 7.0 (R 14)
MATLAB 7.0.1 (R 14SP1)
MATLAB 7.0.4 (R 14SP2)
MATLAB 7.0.4
MATLAB 7.1 (R 14SP3)
MATLAB 7.2 (R 2006a)
MATLAB 7.3 (R 2006b)
MATLAB 7.4 (Release 2007a)
MATLAB 7.5 (Release 2007b)
MATLAB 7.6 (Release 2008a)
MATLAB 7.7 (Release 2008b)
MATLAB 7.8 (Release 2009a)
MATLAB 7.9 (Release 2009b)
MATLAB 7.10 (Release 2010a)
MATLAB 7.11 (Release 2010b)
MATLAB 7.12 (R2011a)
MATLAB 7.13 (R2011b)
MATLAB 7.14 (R2012a)
MATLAB 8.0 (R2012b)
MATLAB 8.1 (R2013a)
MATLAB 8.2 (R2013b)
MATLAB 8.3 (R2014a)

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

System Requirements
Operating System
Windows 8.1
Windows 8
Windows 7 Service
Pack 1
Windows Vista
Service Pack 2
Windows XP Service
Pack 3
Windows XP x64
Edition Service
Pack 2

Processors
Any Intel or
AMD x86
processor
Supporting
SSE2*
instruction set

RAM
Disk Space
1024 MB
1 GB for
(At least
MATLAB only,
2048 MB
recommended) 34 GB for a
typical
installation

* Single-Precision
Floating-Point
Instructions (SSE)

MATLAB Documentation
MATLAB provides extensive documentation, in both Printed &Online Format.
Getting Started - MathWorks
Development Environment
Starting MATLAB
On Windows platforms, start MATLAB by double-clicking the MATLAB
shortcut icon on your Windows desktop.
Quitting MATLAB
To end your MATLAB session, select Exit MATLAB from the File menu in the
desktop, or type quit in the Command Window.
MATLAB Desktop
When you start MATLAB, the MATLAB desktop appears, containing tools
(graphical user interfaces) for managing files, variables, and applications
associated with MATLAB.
You can customize the arrangement of tools and documents to suit your needs.
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.
Desktop Tools
- Command Window: Use the Command Window to enter variables and
run functions and M-files.
5

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

- 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.
To save the input and output from a MATLAB session to a file, use the
diary function.
- Workspace: It displays the Workspace browser, a graphical user interface
that allows you to view and manage the contents of the MATLAB
workspace. It provides a graphical representation of the whos display,
and allows you to perform the equivalent of the clear, load, open, and
save functions.
Matlab Desktop is shown in the flg. Fig.

On-line Help
MATLAB provides on-line help for all built-in functions and commands. To
browse a list of help topics type
>> help
To get help on a specific topic, for example the cosine function, type
>> help cos
Using help is one way to learn about the variety of built-in functions. The help
command is most useful when you know the name of the function, but are
6

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

unsure how to use it. The MATLAB manuals provide cross-referenced and
indexed descriptions of all aspects of using MATLAB
To open the Help browser, click the help button in the toolbar, or type
helpbrowser in the Command Window: See flg. fig.

The Help browser consists of two panes, the Help Navigator pane, which you
use to find information, and the display pane, where you view the information.
Using MATLAB as a calculator
Simply type a mathematical expression into the command window.
The command window prompt is >>.
To enter an expression, type it after the prompt (correct any mistakes by
backspacing) and press return.
MATLAB prints the result back to the command window.
For example:
>> a=6
a=
6
>> b=5
b=
5
>> c=a*b
c=
30
or,
7

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

>> 6*5
ans =
30
Note: When you do not specify an output variable, MATLAB uses the variable
ans, short for answer, to store the results of a calculation.
>>pi
MATLAB responds with
ans =
3.1416
pi is a built-in MATLAB variable.

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Manipulating
Matrices

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Manipulating Matrices
If you start by entering matrix as a list of its elements. You only have to follow
a few basic conventions:
- Separate the elements of a row with blanks or commas.
- Use a semicolon, ; , to indicate the end of each row.
- Surround the entire list of elements with square brackets, [ ].
Example:
To enter the flg. Matrix:
1 2 3
4 5 6
7 8 9
Simply type in the Command Window:
A = [1 2 3; 4 5 6; 7 8 9]
MATLAB displays the matrix you just entered:
A=
1 2 3
4 5 6
7 8 9
Once you have entered the matrix, it is automatically remembered in the
MATLAB workspace. You can refer to it simply as A.
Sum, Transpose, and diag
Now that you have A in the workspace, take a look at what makes it so
interesting: For example, if you want to do the sum of each column, only you
have to enter
sum (A)
MATLAB replies with
ans =
12 15 18
The transpose is given by A; when you write:
A
MATLAB replies with
ans =
1 4 7
2 5 8
3 6 9
When you do not specify an output variable, MATLAB uses the variable ans, short for
answer, to store the results of a calculation.

10

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

The sum of each row produces a column vector; it is given by:


Sum (A)
MATLAB replies with
ans =
6
15
24
The sum of the elements on the main diagonal is obtained with the sum and
the diag functions:
diag (A)
ans =
1
5
9
And
Sum (diag(A))
ans =
15
Addressing matrix elements
The element in row i and column j of A is denoted by A(i,j). For example,
A(3,2) is the number in the third row and second column. For our example,
A(3,2) is 8. So to compute the sum of the elements in the third column of A,
type:
A(1,3) + A(2,3) + A(3,3)
This produces
ans =
18
The Colon Operator
The colon, : , is one of the most important MATLAB operators. It occurs in
several different forms. The expression:
1:10
is a row vector containing the integers from 1 to 10:
1 2 3 4 5 6 7 8 9 10
To obtain nonunit spacing, specify an increment. For example,
100:-7:50
is
100 93 86 79 72 65 58 51
and
11

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

0:pi/4:pi
is
0 0.7854 1.5708 2.3562 3.1416
Expressions
Like most other programming languages, MATLAB provides mathematical
expressions, but unlike most programming languages, these expressions
involve entire matrices. The building blocks of expressions are:
- Variables.
- Numbers.
- Operators.
- Functions.
Overview of MATLAB Variables
- MATLAB variables are created when they appear on the left of an equal
sign. The generic statement >> variable = expression
creates the ''variable'' and assigns to it the value of the expression on the
right hand side.
- You do not need to define or declare a variable before it is used.
- Matrices do not need to explicitly dimensioned, and MATLAB allows
you to increase the size of a matrix as you work.
Variable name
- Begins with a LETTER, e.g., A2z.
- Can be a mix of letters, digits, and underscores_.
- Is case sensitive, e.g., NAME, Name, name are 3 distinct variables. Also
X and x 2 distinct variables.
- Can be of any length.
Although the length can be of any length, MATLAB uses only the first N
characters of the name (where N is the number returned by the function
namelengthmax), and ignores the rest. Hence, it is important to make each
variable name unique in the first N characters to enable MATLAB to
distinguish variables.
All numerical variables in MATLAB are matrices (a mathematical data type
corresponding to a two-dimensional array of numbers).

MATLAB is very careful to follow the rigorous rules of linear algebra, and it
only allows legal operations between matrices, vectors and scalars.
But what about the statement that all numerical variables in MATLAB are
matrices?
MATLAB keeps track of the dimension of each variable. Thus, the statement
>> x = 2
12

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

creates a scalar variable x.


In MATLAB, a scalar is a variable with one row and one column. Scalars are
the simple variables that we use and manipulate in simple algebraic equations.
A vector is a matrix with only one row or only one column. The distinction
between row and column vectors is crucial.
When working with MATLAB you will need to understand how to properly
perform linear algebra using scalars, vectors and matrices. MATLAB enforces
rules on the use of each of these variables.
Complex Variables
Numerical matrix elements may be either real or complex. The type of
element is initially determined at the time the variable is created. However,
matrix elements may change from real to complex if, during an assignment, the
right hand side expression evaluates to a complex number. In this sense, matrix
elements with real values are simply complex numbers with zero imaginary
parts.
Assigning Values to Variables
MATLAB allows you create variables on the fly. To create a variable just use
it on the left hand side of an equal sign.
The following examples show how to assign values to three variables, x, y and
z. It also shows the MATLAB response to the assignment statements.
>> x = 5

x=5

>> z = y + x^0.25

>> y = pi/4

y = 0.7854

z = 2.2807

Note that z exists only as a numerical value, not as the formula with which it
was created.
Use the who command to list the currently active variables. For the preceding
session this results in
>> who
Your variables are:
ans x y z
To view (print) the matrix assigned to any variable, simply enter the variable
name at the prompt.
>> z
z=
2.2807

13

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Special Variables
ans variable which is automatically created whenever a mathematical
expression is not assigned to another variable.
The built-in eps variable* & other variables are given in the flg. table.
*It is used as a tolerance for internal calculations. Initially eps is equal to machine epsilon
You can reset the value of eps, but this is not recommended unless you are very sure you
know what you are doing.

In general you should not try to (re)assign the values of any built-in variables listed in the
table below.

The realmax, realmin, Inf and NaN built-in variables are used to handle
floating point exceptions.
All numerical variables in MATLAB are stored as 32 bit floating point
numbers. The Inf and NaN values appear if a floating point exception occurred
during the calculations.
Strings
MATLAB variables may also be strings, which are matrices of individual
characters. For example, the following statements assign a numerical value to x
and a string value to y.
>> x = 5.2
>> y = 'Mohammad'
The type of variable (numerical or string) is determined when the variable is
created.
Variables
MATLAB does not require any type declarations or dimension statements.
When MATLAB encounters a new variable name, it automatically creates the
variable and allocates the appropriate amount of storage. If the variable already
exists, MATLAB changes its contents and, if necessary, allocates new storage.
For example, num_students = 25
14

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

creates a 1-by-1 matrix named num_students and stores the value 25 in its
single element.
Although variable names can be of any length, MATLAB uses only the first N
characters of the name (where N is the number returned by the function
namelengthmax), and ignores the rest. Hence, it is important to make each
variable name unique in the first N characters to enable MATLAB to
distinguish variables.
N = namelengthmax
N=
63
Numbers
MATLAB uses conventional decimal notation, with an optional decimal point
and leading plus or minus sign, for numbers.
Scientific notation uses the letter e to specify a power-of-ten scale factor.
Imaginary numbers use either i or j as a suffix.
Some examples of legal numbers are:
3
-99
0.0001
9.6397238 1.60210e-20
6.02252e23
1i
-3.14159j
3e5i
Operators
Expressions use familiar arithmetic operators and precedence rules.
+ Addition.
- Subtraction.
* Multiplication.
/ Division.
\ Left division.
Note: .+ .- .* ./ .^ .\ : Element by element operation.
- abs(x)
% absolute value of x.
- exp(x) % e to the x-th power.
- log10(x) % logarithm of x (base 10) .
- sqrt(x) % square root of x.
- sin(x)
% sine of x; x in radians.
- sind(x) % sine of x; x in degrees.
For a list of the elementary mathematical functions, type:
help elfun
MATLAB also provides many more advanced mathematical functions,
including Bessel and gamma functions. Most of these functions accept
complex arguments.
15

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

For a list of more advanced mathematical and matrix functions, type:


help specfun &/or
help elmat
Some of the functions, like sqrt and sin, are built-in. Built-in functions are part
of the MATLAB core so they are very efficient. But the computational details
are not readily accessible. Other functions, like gamma and sinh, are
implemented in M-files.
For built-in functions you cannot see the code. For other functions, you can see
it and even modify it if you want.
Several special functions provide values of useful constants.
pi
3.14159265...
i
Imaginary unit, -1
j
Same as i
eps
Floating-point relative precision, = e52
realmin Smallest floating-point number, 2-1024
realmax Largest floating-point number, (2-)21023
Inf
Infinity
NaN
Not-a-number
Infinity is generated by dividing a nonzero value by zero, or by evaluating well
defined mathematical expressions that overflow, i.e., exceed realmax.
Not-a-number is generated by trying to evaluate expressions like 0/0 or Inf-Inf
that do not have well defined mathematical values. The function names are not
reserved. It is possible to overwrite any of them with a new variable, such as
eps = 1.e-6
and then use that value in subsequent calculations. The original function can be
restored with
clear eps
Examples of Expressions
Example-1:
r = (1+sqrt(5))/2
r=
1.6180
Example-2:
a = abs(3+4i)
a=
5

16

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Working with Matrices


This section introduces you to other ways of creating matrices:
- Generating Matrices.
- The load Function.
- M-Files.
- Deleting Rows and Columns.
Generating Matrices
MATLAB provides four functions that generate basic matrices:
- zeros All zeros.
- ones All ones.
- rand Uniformly distributed random elements.
- randn Normally distributed random elements.
Here are some examples:
Z = zeros(2,4)
Z=
0 0 0 0
0 0 0 0
F = 5*ones(3,3)
F=
5 5 5
5 5 5
5 5 5
N = rand(1,6)
N=
0.9169 0.4103
R = randn(4,4)
R=
0.6353 0.0860
-0.6014 -2.0046
0.5512 -0.4931
-1.0998 0.4620

0.8936 0.0579 0.3529 0.8132

-0.3210
1.2366
-0.6313
-2.3252

-1.2316
1.0556
-0.1132
0.3792

The load Function


The load loads all the variables from the MAT-file matlab.mat, if it exists,
or returns an error if the file doesn't exist.
load looks for a file named filename.mat and treats it as a binary MATfile. If filename has an extension other than .mat, load treats the file as
ASCII data.
17

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

load filename X Y Z ... loads just the specified variables X, Y, Z, etc.


from the MAT-file.
An easy way to read data into MATLAB in many text or binary formats is to
use Import Wizard.
M-Files
You can create your own matrices using M-files, which are text files containing
MATLAB code. Use the MATLAB Editor or another text editor to create a file
containing the same statements you would type at the MATLAB command
line. Save the file under a name that ends in .m*.
Note (related to file name in general): Files that contain MATLAB commands
should be named with a suffix of ".m", e.g., something.m. These include, but
not restricted to, script m-files and function m-files. To use it, just refer to it by
name, without the suffix, e.g.,
>> something
File Name
Files that contain MATLAB commands should be named with a suffix of ".m",
e.g., something.m. These include, but not restricted to, script m-files and
function m-files.
To use it, just refer to it by name, without the suffix, e.g.,
>> something
Deleting Rows and Columns
You can delete rows and columns from a matrix using just a pair of square
brackets. Example:
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
Then, to delete the second column of A, use
A (:,2) = [ ]
This changes A to
A=
1 3
4 6
7 9
To delete the second line of A, use
>> A(2,:) = [ ]
This changes A to
A=
18

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

1 3
7 9
If you delete a single element from a matrix, the result is not a matrix anymore.
So, expressions like
>> A(1,2) = [ ]
??? Subscripted assignment dimension mismatch.

i.e. result in an error.

Special Characters

+, -, *, / and \ are the arithmetic operators.


: range delimiter, e.g.,
>> x = [1:2:9]
% x =1 3 5 7 9
this

If is omitted a value of 1 (unit increment) is used. Example:


>> x = [1:5] % x = 1 2 3 4 5
; to indicate the end of each row; suppresses screen output
Example-1 (end of each row):
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
Example-2 (suppresses screen output):
Suppressing Output with Semicolon
In the preceding examples it was useful to have MATLAB print the results of
the calculations. This is not always the case.
MATLAB will print the result of every assignment operation unless the
expression on the right hand side is terminated with a semicolon.
Rather, it is a convenience that allows multiple statements to be executed
without printing the intermediate results. For example, most lines in m-files
end with semicolons because only the final results of the calculations are of
interest.
To see how the semicolon works enter the following statements exactly as
shown, ending each line with a carriage return. Do not enter the prompt
character, >>.
>> x = pi/3;
>> y = sin(x)/cos(x);
>> z = y - tan(x);
>> z
z=
19

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

0
>> y
y=
1.7321
The last two lines do not end in semicolons so MATLAB prints the results of
z and y.
, command delimiter, e.g.,

>> x = [1:2:9], y = [1:9] % two statements on the same line.


% anything after % (and until end of line) is treated as comments, e.g.,
>> x = 1:2:9; % x = [1 3 5 7 9];
... statement continuation, e.g.,
>> x = [ 1 3 5 ...
7 9]; % x = [1 3 5 7 9] splitted into 2 lines.
' matrix transposition, e.g.,
>> x = [1:2:9]';
% x changed from row vector to column vector.
>> clear A* % clears all variables that start with A.
. precede an arithmetic operator to perform an elemental operation instead
of matrix operation, e.g.,
>> x = 2:2:6
x=
246
>> y = [1:1:3]
y=
123
>> z =x./y
z=
222

20

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Graphics

21

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Review
- MATLAB provides a wide variety of techniques to display data
graphically.
- MATLAB provides interactive tools enabling you to manipulate graphs to
achieve results that reveal the most information about your data.
- You can also annotate and print graphs for presentations, or export graphs
to standard graphics formats for presentation in web browsers or other
media.

Creating a Graph
The type of graph depends on the nature of the data and the purpose of the
graph. MATLAB predefines many graph types, such as:
- line, bar, histogram, and pie graphs.
- 3-D graphs.

Two basic ways to create graphs in MATLAB:


- Using plotting tools to create graphs interactively.
- Using commands (where you enter in the Command Window), or create
plotting programs.
Both approaches might be combined: For example, issue a plotting command
to create a graph and then modify the graph using one of the interactive tools.

Exploring Data
Once a graph is created, specific information about the data can be extracted
such as peak value in a plot, average value,..

Editing the Graph Components


Graphs are composed of objects, which have properties you can change. The
data used to create a line graph are properties of the line. You can change the
data without actually creating a new graph. For example:
- The axes used to define the coordinate system of the graph has
properties that define the limits of each axis, the scale, color, etc.
- The line used to create a line graph has properties such as color, type of
marker used at each data point (if any), line style, etc.

Annotating Graphs
Annotations are the text, arrows, and other labels added to graphs to help
viewers see what is important about the data.

Printing and Exporting Graphs


You can print your graph on a printer. The print previewer enables to view
how the graph will look when printed. It enables you to add headers, footers, a
date, and so on.
22

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

The print preview dialog lets you control the size, layout, and other
characteristics of the graph (select Print Preview from the figure File menu).
Exporting a graph means creating a copy of it in a standard graphics file
format, such as TIF (TIFF- Tag Image File Format), JPEG (Joint Photographic
Experts Group, or EPS (EPS-Encapsulated PostScrip). You can then import the
file into a word processor, include it in an HTML document, or edit it in a
drawing package (select Export Setup from the figure File menu).

Adding and Removing Figure Content


By default, when you create a new graph in the same figure window, its data
replaces that of the graph that is currently displayed, if any.
You can manually remove all data, graphics and annotations from the current
figure by typing CLF in the Command Window (or by selecting Clear Figure
from the figures Edit menu).

Saving Graphs to Reload into MATLAB


There are two ways to save graph:
- Save the graph as a FIG-file (select Save from the figure File menu). FIGfiles are a binary format that saves a figure in its current state. This means
that all graphics objects and property settings are stored in the file when
you create it. You can reload the file into a different MATLAB session,
even if you are running MATLAB on a different type of computer.
- Generate MATLAB code that can recreate the graph (select Generate MFile from the figure File menu).

Graph Components
- MATLAB displays graphs in a special window known as a figure.
- To create a graph, you need to define a coordinate system.
- The actual visual representation of the data is achieved with graphics
objects like lines and surfaces.
- The objects are drawn within the coordinate system defined by the axes,
which MATLAB automatically creates specifically to accommodate the
range of the data.
- The actual data is stored as properties of the graphics objects.

Creating Line Plots with MATLAB


We describe how to plot y = f(x) by connecting the data points with a line.
Two-dimensional line and symbol plots are created with the plot command. In
its simplest form plot takes two arguments:
>> plot(xdata,ydata)
where xdata & ydata are vectors containing the data.
Note that:
23

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

- xdata & ydata must be the same length and both must be the same type,
i.e., both must be either row or column vectors.
- Additional arguments to the plot command provide other options
including the ability to plot multiple data sets, and a choice of colors,
symbols and line types for the data.

A simple line plot


Here are the MATLAB commands to create a simple plot of y = sin(3*x) from
0 to 2*pi.
>> x = 0:pi/30:2*pi; % x vector, 0 <= x <= 2*pi, increments of pi/30.
>> y = sin(3*x);
% vector of y values.
>> plot(x,y)
% create the plot.
>> xlabel('x (radians)'); % label the x-axis.
>> ylabel('sine function'); % label the y-axis.
>> title('sin(3*x)');
% put a title on the plot.
The effect of
the labeling
commands,
xlabel, ylabel,
and title are
indicated by
the text and red
arrows in the
figure. Don't
skimp on the
labels!

Logarithmic axis scaling


Log-log and semi-log plots are created with commands that act just like the
plot command. They are summarized below:
Command Name

Plot type

Loglog(x,y)

log(y) versus log(x)

Semilogx(x,y)

y versus log(x)

Semilogy(x,y)

log(y) versus x

24

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Creating Symbol Plots with MATLAB


Changing symbol or line types
The symbol or line type for the data can by changed by passing an
optional third argument to the plot command. For example:
>> plot(x,y,'o'); plots data in the x and y vectors using circles drawn in the
default color, &
>> plot(x,y,'r:'); plots data in the x and y vectors by connecting each pair of
points with a red dashed line.
The third argument of the plot command is a one, two or three character string
of the form 'cs', where:
- 'c' is a single character indicating the color &
- 's' is a one or two character string indicating the type of symbol or line
(The color selection is optional).
Allowable color and symbols types are summarized in the following tables.

Refer to ``help plot'' for further information.

A simple symbol plot


This example shows you how to plot data with symbols. This type of plot is
appropriate, for example, when connecting data points with straight lines
would give the misleading impression that the function being plotted is
continuous between the sampled data points.
Here are the MATLAB commands to create a symbol plot with the data
generated by adding noise to a known function.
>> x = 0:0.1:2; % generate the x-vector.
>> y = 5*x.*exp(-3*x);
25

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

>> plot(x,y,'o'); % and plot with symbols


>> xlabel('x (arbitrary units)'); % add axis labels and plot title.
>> ylabel('y (arbitrary units)');
>> title('Plot of y = 5*x*exp(-3*x)');
See flg. Figures.

26

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Putting Multiple Curves on the Same Plot


We will describe how to plot y1 = f1(x), y2 = f2(x), ... yn = fn(x) on the same
plot, and how to label these curves with the legend command.

Passing multiple data pairs to the plot command


The plot command will put multiple curves on the same plot with the following
syntax plot(x1,y1,s1,x2,y2,s2,x3,y3,s3,...).

The legend command


The legend is used to label the different data curves when more than one curve
is drawn on the same plot.
The syntax is legend('label1','label2',...) Where label1, etc are strings used to
create the legend.

An example of putting multiple curves on a plot


Here are the MATLAB commands to create a symbol plot with the data
generated by adding noise to a known function. The original function is drawn
with a solid line and the function plus noise is plotted with open circles.
>> x = 0:0.1:2; % generate the x-vector.
>> y = 5*x.*exp(-3*x); % and the "true" function, y.
>> yn = y + 0.02*randn(size(x)); % Create a noisy version of y.
>> plot(x,y,'-',x,yn,'ro'); % Plot the true and the noisy.
>> xlabel('x (arbitrary units)'); % add axis labels and plot title.
>> ylabel('y (arbitrary units)');
>> title('Plot of y = 5*x*exp(-3*x) + noise');
>> legend('true y','noisy y');
Note that the ``.*'' operator is necessary when multiplying the vector x by the
vector exp(-3*x). The preceding statments & plot are given in the next figures.

27

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

Generating M-file
From File menu, select Generate M-File as shown below.

28

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

The generated code is shown in the following fig.

29

CEN340-Introduction to MATLAB, CCIS CEN Department, 1434/1435, Dr. S. Rahal

References

MATLAB Documentation - MathWorks


http://www.mathworks.com/help/matlab/index.html

MATLAB Product Description, R2014a.


http://www.mathworks.com/help/matlab/learn_matlab/product-description.html

Introduction, What Is MATLAB?


http://cimss.ssec.wisc.edu/wxwise/class/aos340/spr00/whatismatlab.htm

INTRODUCTION TO MATLAB FOR ENGINEERS, William J.


Palm, 3-d edition, McGraw-Hill, 2011.

30

You might also like