Matlab Tutorial

Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

The Hong Kong Polytechnic University

Industrial Centre

MATLAB
in Basic Scientific Computing
Alan Yu and Ivan Lam
2 0 10
Table of Contents

Overview.............................................................................................................................................. 1
1. Development Environment .............................................................................................................. 2
1.1 Starting MATLAB ............................................................................................................... 2
1.2 MATLAB Desktop .............................................................................................................. 2
2. Beginning of MATLAB .................................................................................................................. 9
2.1 MATLAB as simple calculator ............................................................................................ 9
2.2 Variable............................................................................................................................. 10
2.2.1 Scalar Variables ............................................................................................................. 10
2.2.2 Vectors ........................................................................................................................... 11
2.3 Matrices ............................................................................................................................. 13
2.4 String.................................................................................................................................. 13
3. Mathematical Operations ............................................................................................................... 14
3.1 Matrices and Linear Algebra ............................................................................................. 14
3.2 Scalar Function .................................................................................................................. 17
4. MATLAB Graphics ................................................................................................................... 20
4.1 Basic Plotting ..................................................................................................................... 20
4.2 Formatting Graph............................................................................................................... 25
4.3 Creating Specialized Plots ................................................................................................. 30
5. Polynomials with MATLAB ......................................................................................................... 34
5.1 Polynomial Operations ...................................................................................................... 34
5.2 Data Analysis and Curve Fitting........................................................................................ 37
6. 3-D Visualization ........................................................................................................................... 39
6.1 Line plots of 3D data ......................................................................................................... 39
6.2 Preparing data .................................................................................................................... 39
6.3 Contour, Mesh and Surface Plots ...................................................................................... 40
6.4 Colormap ........................................................................................................................... 44
7. File I/O Function............................................................................................................................ 46
7.1 Open and Close file ........................................................................................................... 46
7.2 Written file ......................................................................................................................... 46
7.3 Read File ............................................................................................................................ 47
8. M-file Programming ...................................................................................................................... 49
8.1 Scripts ................................................................................................................................ 49
8.2 Functions............................................................................................................................ 50
8.3 Flow Control ...................................................................................................................... 51
9. Creating Graphical User Interfaces ............................................................................................... 55
9.1 GUI with MATLAB .......................................................................................................... 55
9.2 Programming GUIs ............................................................................................................ 59
10. Some MATLAB function descriptions ........................................................................................64
Overview
MATLAB is a high-level programming application for solving mathematical and scientific
problems. It helps you handle numerical calculations and output results in the form of high-quality
graphics. It also enables you to construct customized graphical user interfaces for specific
computation problems.
This module provides a comprehensive coverage of the latest scientific computing technology in
engineering and science and complements theoretical learning by providing practical knowledge in
applying latest computing technology for research, design, and development. After studying the
course, students will be able to
• use MATLAB to solve mathematical problems, including data analysis, statistical analysis,
matrix, and linear algebra
• solve problems in familiar mathematical notation
• analyse data by using 2D and 3D visualization plots
• use M-files to construct user defined mathematical functions
• construct programs with flow control functions
• construct graphical user interfaces for specific mathematical functions
• import data from and export data to other applications

Page 1
1. Development Environment
1.1 Starting MATLAB
To run MATLAB on a PC, double-click the MATLAB icon from your Windows desktop.

MATLAB prompts you with two “>>” when it is ready to accept a command from you.

When starting MATLAB, you should see a message:

This is a Classroom License for instructional use only.


Research and commercial use is prohibited.

MATLAB desktop keyboard shortcuts, such as Ctrl+S, are now customizable.


In addition, many keyboard shortcuts have changed for improved consistency
across the desktop.

To customize keyboard shortcuts, use Preferences. From there, you can also
restore previous default settings by selecting "R2009a Windows Default Set"
from the active settings drop-down list. For more information, see Help.

Click here if you do not want to see this message again.


>>

1.2 MATLAB Desktop


MATLAB has following windows

• Workspace
• Command History
• Command Windows
• Current Directory

Page 2
Command Windows

MATLAB inserts a blank line to separate command lines. You can eliminate it by using the
following command:

>> format compact

Page 3
To browse a list of help topics, type:

>> help

Page 4
To get help on a specific topic, for example the command ‘sum’, type:

>> help sum

Page 5
>> help mean

Command History

Command History displays all previous command. Double click the commands in command
history window will also re-activate that command.

Page 6
Current Directory Browser
All files in current directory are shown in current directory browser. You can change the current
directory path by using the pathname edit box. You can also open a file by double-click on it in
Current Directory Browser.

Icons Function
Back
Forward
Find and Search folders
Create new folder, Scripts, Functions and Class
View or change the current folder

Workspace Browser
The MATLAB workspace consists of a set of variables defined during a MATLAB session and
stored in memory. Variables can be defined by
1. running commands and functions
2. running M-files programming
3. importing from data files

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

Page 7
This data is not saved after you exit MATLAB. All data can be saved by:
1. Selecting “save Workspace As” from the File menu; or
2. Using save function – This is used for saving all data to MAT-file.

The Start button provides easy way to access tools, toolboxes, shortcuts, desktop tools,
documentation and demos.

Page 8
2. Beginning of MATLAB
MATLAB as simple calculator

You simply type an equation and MATLAB will do the calculation for you.
>> cos(pi)
ans =
-1

pi is a pre-defined variable in MATLAB. It equals to π. A new variable ‘ans’ is defined. The value
of variable can be displayed when double click this variable in Workspace Window. The command
“cos” is used to calculate cosine argument in radian and the command “cosd” is used to calculate
cosine argument in degree. The ans variable is automatically created whenever a mathematical
expression is not assigned to another variable.
>> pi

MATLAB responds with


ans =
3.1416

You can print the value of this variable by simply type in the name of variable.
>> ans
ans =
3.1416

You will find that MATLAB inserts blank lines to separate commands unless you instruct it to
eliminate them with the command:
>> format compact

You can switch to default format using the following command:


>> format

The display format can be set to be a fixed-point format with 15 digits.


>> format long
>>pi
ans =
3.14159265358979

Or you can set to approximation by ratio of small integers


>> format rat
>> pi
ans =
355/113

Display format to be fixed format for dollars and cents.


>> format bank
>> pi
ans =
3.14

Page 9
MATLAB automatically echoes the result unless you end your variable definition and calculation
with a semicolon.
>> sin(pi);

pi is a built-in MATLAB variable. The preceding command is actually a request for MATLAB to
print the value of this variable.
Try the following examples
>> sin(pi/4)
ans =
0.7071
>> sind(45)
ans =
0.7071
>> 2^(log2(4))
ans =
4
>> sqrt(9)
ans =
3

It is convenience since it allows multiple statements to be executed without printing the


intermediate results. You can suppress the result by using semicolon at the end of each function.
>> pi/3;
>> sin(ans)/cos(ans);
>> ans - tan(pi/3);

2.2 Variable
MATLAB variables are created when they appear on the left of an equal sign.
>> variable = expression

Variables include
• Scalars
• Vectors
• Matrices
• Strings
Characteristics of MATLAB Variables:
• Variable names must begin with an alphanumeric letter.
• Following that, any number of letters, digits and underscores can be added, but only the first
19 characters are retained.
• MATLAB variable names are case sensitive so x and X are different variables.

2.2.1 Scalar Variables


In MATLAB, a scalar is a variable with one row and one column.

Creating scalars
To create a scalar you simply type following command in Command window.
>> x = 4;

Page 10
>> y = 5;
>> z = x + y;

Scalar operations
MATLAB supports the standard scalar operations using an obvious notation. The following
statements demonstrate scalar addition, subtraction, multiplication and division.
>> x = 5;
>> y = 3;
>> z = x + y
>> s = x - y
>> a = x * y
>> d = x/y
>> d2 = y\x
>> p = x^y

2.2.2 Vectors
In MATLAB, a vector is a matrix with either one row or one column.

Creating vectors with ones, zeros, linspace and logspace


The ones, zeros, linspace, and logspace functions allow for explicit creations of vectors of a
specific size and with a prescribed spacing between the elements.
The ones and zeros functions have two arguments. The first one is the number of rows in the
matrix you wish to create. The second one is the number of columns. To create a row or a column
vector, set the appropriate argument of ones and zeros to one.
To create a row vector of length 5 with single row, filled with ones use
>> x=ones(1,5)
x=
1 1 1 1 1

To create a column vector of length 5 with single row filled with zeros, use
>> y=zeros(5,1)
y=
0
0
0
0
0

The linspace and logspace functions create vectors with linearly spaced or logarithmically
spaced elements, respectively. Here are examples including the MATLAB output.
>> x = linspace(1,5,5)
x=
1 2 3 4 5
>> y = logspace(1,5,5)
y=
10 100 1000 10000 100000

Page 11
The third argument of both linspace and logspace is optional. The third argument is the number
of elements to be used between the range specified with the first and second arguments.

Addressing vector elements


Location of vector can be addressed by using
>> x = linspace(11,15,5)
x=
11 12 13 14 15
>> x(2)
ans =
12

Address is counted from left corner, from top to bottom or from left to right.

Increasing the size of a vector (or scalar)


We can also increase the size of a vector simply by assigning a value to an element.
>> x = linspace(1,5,5)
x=
1 2 3 4 5
>> x(7) = -9
x=
1 2 3 4 5 0 -9

x(6) is assigned to zero.

Colon notation
Colon notation can be used to create a vector. The format of this command is shown as below:

>> x = xbegin:dx:xend
or
>> x = xbegin:xend

where xbegin and xend are the range of values covered by elements of the x vector, and dx is the
optional increment. The default value of dx is (unit increment). The numbers xbegin, dx, and
xend may not be integers. For example
>> x = 1.1:5.1
x=
1.1 2.1 3.1 4.1 5.1

To create a column vector, append the transpose operator to the end of the vector-creating
expression
>> y = (1:5)’
y=
1
2
3
4
5

Page 12
2.3 Matrices
In MATLAB a matrix is a variable with more than one row and one column
Creating matrices:
For example, the statement
>> A = [1 2;3 4]
creates the 2 by 2 matrix ans assigned to variable A
A=
1 2
3 4

Addressing matrix elements


There are two methods to address matrix elements:
1. Addresses are counted from upper left corner, from top to bottom, from left to right.
2. If A is a matrix, then A(2,3) is the element in the second row and third column. The following
statements create a 3 by 3 matrix, print the (2,3) element and change the (3,2) element.
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
>> A(2,3)
ans =
6

You can change the value of an element in a matrix.


>> A(3,2) = -5
A=
1 2 3
4 5 6
7 -5 9

2.4 String
You define string by
>>a='test'
a=
test

MATLAB converts a string to ASCII codes before performing simple calculation.


>>a='test';
>>a+a
ans =
232 202 230 232

If you want to append the string


>>a='test';
>>[a a]
ans =
testtest

Page 13
3. Mathematical Operations
3.1 Matrices and Linear Algebra
Addition and Subtraction
Addition and subtraction of matrices are defined just as the ways for arrays, element-by-element.
Adding A to B and then subtracting A from the result recovers B.
>> A = [1 1 1;1 2 3;1 3 6];
>> B = [8 1 6;3 5 7;4 9 2];
>> X = A+B
X=
9 2 7
4 7 10
5 12 8
>> Y = X-A
Y=
8 1 6
3 5 7
4 9 2

Addition and subtraction require both matrices to have the same dimension, or one of them must be
a scalar. If the dimensions are incompatible, an error results.
>> C = [1:3;4:6];
>> X = A+C
??? Error using ==> +
Matrix dimensions must agree.

Vector Products
A row vector and a column vector of the same length can be multiplied in either order. The result
is either a scalar, the inner product, or a matrix, the outer product.
>> u = [2 3 4];
>> v = [-2 0 2]';
>> x = u*v
x=
4
>> x = v*u
x=
-4 -6 -8
0 0 0
4 6 8

Matrix Multiplication
MATLAB uses a single asterisk to denote matrix multiplication. The next two examples illustrate
the fact that matrix multiplication is not commutative; A*B is usually not equal to B*A.

Page 14
>> A*B
ans =
15 15 15
26 38 26
41 70 39
>> B*A
ans =
15 28 47
15 34 60
15 28 43

A matrix can be multiplied on the right by a column vector and on the left by a row vector.
>> x = A*v
x=
0
4
10
>> y = u*B
y=
41 53 41

Solving Linear Systems of Equations


Matrices are helpful in rewriting a linear system in a very simple form. The algebraic properties of
matrices may then be used to solve systems. First, consider the linear system:
ax + by + cz = p
dx + ey + fz = q
gx + hy + iz = r
Set the matrices
⎡a b c ⎤ ⎡ p⎤ ⎡ x⎤
A = ⎢d e f ⎥ , C = ⎢ q ⎥ , and X = ⎢⎢ y ⎥⎥
⎢ ⎥ ⎢ ⎥
⎢⎣ g h i ⎥⎦ ⎢⎣ r ⎥⎦ ⎢⎣ z ⎥⎦
Using matrix multiplications, we can rewrite the above linear system as the matrix equation
A⋅ X = C
To solve A ⋅ X = C , we can use the matrix inverse, if it exists:
1. Find A-1.
2. Multiply on left by A-1 to get A-1AX = A-1C.
3. The solution is X = A-1C.

By MATLAB, Y=inv(A) returns the inverse of the square matrix A.

Page 15
For example: To solve the following equations.
x+ y+z =0
x − 2 y + 2z = 4
x + 2y − z = 2
>> A = [1 1 1;1 -2 2;1 2 -1]
A=
1 1 1
1 -2 2
1 2 -1
>> C = [0 4 2]'
C=
0
4
2
>> X = inv(A)*C
X=
4.0000
-2.0000
-2.0000
Therefore the linear system has one solution:
x = 4, y = -2 and z = -2

Element by Element Operations on Arrays


When performing the array operations in MATLAB, one has to pay extra attention. Essentially
there are two types of operations involving arrays.
1. Element by element operations.
2. Vector-Matrix operations.
Confused by these can lead to real difficulties. The next session shows the formation and addition
of two vectors:
>> a = [1 2 3];b = [2 5 8];
>> a+b
ans =
3 7 11

Let’s try to multiply them:


>> a*b
??? Error using ==> *
Inner matrix dimensions must agree.

What happened? The multiplication symbol by itself, when applied to vectors or matrices, is
interpreted to mean matrix multiplication. We could do this by transposing the second vector:
>> a*b'
ans =
36

This gives (1*2+2*5+3*8) = 36, the usual scalar product of two vectors.

Page 16
If we want the element by element product, we must put a period before multiplication symbol:
a.*b
ans =
2 10 24

The same procedure must be followed in doing division and exponentiation. For example, if you
want the square of each element in a vector you must use:
>> a.^2
ans =
1 4 9

Forgetting the period will lead to:


>> a^2
??? Error using ==> ^
Matrix must be square.

One of the main features of MATLAB is that it provides vector and array results with most of its
built-in functions. The fact that sin(t), with t, a vector gives the value of sin of each element makes
it trivial to look at a plot of the function.

3.2 Scalar Function


Most of MATLAB commands are functions. Some of these functions represent mathematical
functions and operate on scalars as well as on matrices.

Useful functions and operations in MATLAB


Using MATLAB as a calculator is easy.
Example: Compute 5 sin( 2.5 3− pi ) + 1 / 75 . In MATLAB, this is done by simply typing in
>> 5*sin(2.5^(3-pi))+1/75
ans =
3.8617
at the prompt. Be careful with parentheses and don’t forget to type * whenever you do
multiplications!

If input matrix, sine function will output matrix.


>> x = 0:0.5:3;
>> sin(x)
ans =
0 0.4794 0.8415 0.9975 0.9093 0.5985 0.1411

max and min return the largest and smallest values in a vector or matrix.
- max and min return a scalar fro a vector.
- max and min return a vector for a matrix
If called with a matrix as its argument, max returns a row vector in which each element is the
maximum value of each column of the input matrix. The max function can also return a second
value: the index of the maximum value in the vector or row of the maximum value down a column.
To get this, assign the result of the call to max to a two-element vector instead of just a single
variable.

Page 17
>> x = [1 0;2 9;3 3;4 8];
>> [a b] = max(x)
a=
4 9
b=
4 2
where a is the maximum value of the matrix and b is the index of that value. The MATLAB
function min is exactly used in the same way as max but returning the smallest value.

sum and prod are another two useful functions for matrices.
>> x=[1:3;4:6;7:9];
>> sum(x)
ans =
12 15 18
>> sum(sum(x))
ans =
45
If x is a vector, sum(x) is the sum of all the elements of the vector x in the form of a scalar. For
matrices, sum(x) sums the columns and return a vector.
The following are many built-in functions in MATLAB:
Function Description
sin Sine argument in radian
cos Cosine argument in radian
tan Tangent argument in radian
asin inverse sine, result in radian
acos inverse cosine, result in radian
atan inverse tangent, result in radian
sind sin argument in degree
cosd cosine argument in degree
tand tangent argument in degree
asind inverse sine, result in radian
acosd inverse cosine, result in radian
atand inverse tangent, result in radian
exp exponential
max maximum elements of an array
min minimum elements of an array
sum sum of array elements
prod product of array elements
cumsum cumulative sum of elements
cumprod cumulative product of elements
size array dimensions
length length of vector
mean average or mean value of arrays
median median value
std standard deviation
sort sort elements in ascending order
exp exponential
factorial factorial function
log natural logarithm
log10 common (base 10) logarithm

Page 18
Round Floating Point numbers to Integers
MATLAB has functions to round floating-point numbers to integers. These are round, fix, ceil,
and floor. The next few examples work through this set of commands and a couple more
arithmetic operations.
>> x = -1:0.2:1;
>> round(x)
ans =
-1 -1 -1 0 0 0 0 0 1 1 1
>> fix(x)
ans =
-1 0 0 0 0 0 0 0 0 0 1
>> ceil(x)
ans =
-1 0 0 0 0 0 1 1 1 1 1
>> floor(x)
ans =
-1 -1 -1 -1 -1 0 0 0 0 0 1

Pseudorandom numbers
MATLAB has functions to give you pseudorandom numbers.

Function Description example


rand(M,N) This function give a M-by-N matrix >>rand(3,4)
containing uniform distribution ans =
pseudorandom numbers .They are
between 0 and 1. 0.8003 0.9157 0.6557 0.9340
0.1419 0.7922 0.0357 0.6787
0.4218 0.9595 0.8491 0.7577
randn(M,N) This function give a M-by-N matrix >>randn(3,4)
containing normally distribution ans =
pseudorandom numbers.
0.7269 -0.7873 -1.0689 1.4384
-0.3034 0.8884 -0.8095 0.3252
0.2939 -1.1471 -2.9443 -0.7549
randi([A,B],M,N) This function give a M-by-N matrix >>randi([-10,10],3,4)
containing pseudorandom integers. ans =
Those numbers are drawn from the
discrete uniform distribution on A to 9 -2 -7 3
B -10 6 0 4
-1 6 -1 5

Page 19
4. MATLAB Graphics
4.1 Basic Plotting
The plot command suffices for basic 2-D graphics. If x and y are equal-length vectors, plot(x,y)
will plot the values of y on the y-axis versus those of x on the x-axis. If the first argument is
omitted, it will be taken to be the indices of y.

plot(y) plots the columns of Y versus their


index if Y is a real number.
plot(x,y) plots the lines defined by x versus y.
plot(x1,y1,x2,y2,x3,y3,…) plots all lines defined
by xn versus yn pairs.

Examples:
>> x = -pi:0.1:pi;
>> y = sin(x);
>> plot(y)

>> x = -pi:0.1:pi;
>> y = cos(x);
>> plot(x,y)

>> t = 0:0.1:2*pi;
>> plot(sin(t),cos(t));

Page 20
>> x = -10:10;
>> y = x.^2;
>> plot(x,y,x,2*y,x,3*y,x,4*y)
>> h = findobj(gcf,'LineWidth',.5);
>> set(h,'linewidth',2)

Specifying Line style, Colors and Markers


The basic plotting functions accept character-string arguments that specify various line styles,
marker symbols, and colors for each vector plotted. In the general form,

plot(x,y,’linestyle_marker_color’) linestyle_marker_color is a character string constructed from:


• A line style
• A marker type
• A predefined color specifier

The line style choices are: The marker type choices are:
Symbol Line Style Symbol Marker Type
- solid line . point
: dotted line o circle
-. dash-dot line x x-mark
-- dashed line + plus
* star
s square
The color choices are: d diamond
Symbol Color v triangle (down)
y yellow ^ triangle (up)
m magenta < triangle (left)
c cyan > triangle (right)
r red p pentagram
g green h hexagram
b blue
w white
k black

Page 21
For example:
Plots a green dotted line and places square
markers at each data point.

>> x = 0:0.1:2*pi;
>> y = sin(x);
>> plot(x,y,':sg')

If you specify a marker type, but not a line style,


MATLAB draws only the marker.

>> x = -10:0.2:10;
>> y = x.*sin(x);
>> plot(x,y,'x')

You can plot more than one function on the


same figure, using a different line style, color
and point marker for each curve.
>> x = linspace(0,2*pi,50);
>> y = sin(x);z = cos(x);
>> plot(x,y,'ro:',x,z,'m--*',y,z,'g^-')

>> x = -10:0.2:10;
>> y = x.*sin(x);
>> plot(x,y,'pg',x,y,'m-')

Page 22
Specifying the Color and Size of Lines
You can also specify the size of the marker and, for markers that are closed shapes, you can specify
separately the color of the edges and the face.
• LineWidth – specifies the width of the line in units of points.
• MarkerEdgeColor – specifies the color of the marker or the edge color for filled markers.
• MarkerFaceColor – specifies the color of the face of filled markers.
• MarkerSize – specifies the size of the marker in units of points.

For example:

>> x = -pi:pi/10:pi;
>> y = tan(sin(x))-sin(tan(x));
>> plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)

Figure Windows
The plot function automatically opens a new figure window if there are no figure windows already
on the screen. If a figure window exists, plot plots the graph in that window by default. To open a
new figure window and make it the current figure, type
figure
To make an existing figure window current, type
figure(n)
Where n is the number of the figure title bar. The results of subsequent graphics commands are
displayed in the current window.

Adding Plots to an Existing Graph


By adding more sets of parameters, you can plot as many different functions on the same figure as
you want. When plotting more than one curve on the same graph, it is useful to differentiate the
different functions based on the colour and point marker. This same effect can also be achieved by
using the hold on and hold off commands.
For example:

>> x = linspace(0,2*pi,50);
>> y = sin(x);
>> plot(x,y,'ro:')
>> z = cos(x);
>> plot(x,z,'m--*')
>> hold on
>> plot(y,z,'g^-')
>> hold off

Page 23
Always remember that if you use the hold on command, all plots from then on will be generated on
one set of axes, without erasing the previous plots, until the hold off command is issued.

Displaying Multiple Plots per Figure


You can display multiple plots in the same figure window and print them on the same piece of
paper with the subplot function.

subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ith
subplot for the current plot. The plots are numbered along the top row of the figure window, then
the second row, and so forth.

For example:

>> subplot 321


>> t = linspace(0,2*pi,4);
>> plot(sin(t),cos(t))
>> subplot 322
>> t = linspace(0,2*pi,5);
>> plot(sin(t),cos(t))
>> subplot 323
>> t = linspace(0,2*pi,6);
>> plot(sin(t),cos(t))
>> subplot 324
>> t = linspace(0,2*pi,7);
>> plot(sin(t),cos(t))
>> subplot 325
>> t = linspace(0,2*pi,8);
>> plot(sin(t),cos(t))
>> subplot 326
>> t = linspace(0,2*pi,9);
>> plot(sin(t),cos(t))

>> x = linspace(0,1,100);
>> y = exp(-x).*cos(6*pi*x);
>> w = exp(-x); z = -w;
>> subplot(2,2,1)
>> plot(x,y)
>> subplot(2,2,2)
>> plot(x,w,'r:',x,z,'r:')
>> subplot(2,1,2)
>> plot(x,y,x,w,'r:',x,z,'r:')

Page 24
>> x = 0:0.05:2*pi;
>> y = sin(x);
>> subplot(2,1,1);
>> plot(x,y,'r')
>> subplot(2,1,2);
>> plot(x,y,'b');
>> axis off
>> axes('Position',[0.6 0.2 0.3 0.2])
>> plot(x,y,'g')

4.2 Formatting Graph


When creating presentation graphics, you may want to add labels and annotations to your graph to
explain your data. MATLAB provides mechanisms that let you:
• Add a title at the top of an axes
• Add a legend
• Add labels to axes
• Add free-form text annotations anywhere on your graph
• Add arrows and lines anywhere on your graph

The following figure shows a graph that uses all of these labels and annotations. Click on any one
of the labels and annotations in this figure to get more information about how to create the label or
annotation.

Title

Legend

Arrow

Test annotation

Axes label

Page 25
Title, Legend, Label and Text Function
Labelling is also important in plotting of graphs. You can give your plot a title, x-axis label, y-axis
label, and text on the actual plot. All of the above commands are issued after the actual plot
commands are done.

title('string') outputs the string at the upper centre of the current axes.

legend('string1','string2',...) displays a legend in the current axes using the specified strings to
label each set of data.
legend('off') removes the legend in the current axes.
legend(...,pos) uses pos to determine where to place the legend.
• pos = -1 places the legend outside the axes boundary on the right side.
• pos = 0 places the legend inside the axes boundary, obscuring as few points as possible.
• pos = 1 places the legend in the upper-right corner of the axes(default).
• pos = 2 places the legend in the upper-left corner of the axes.
• pos = 3 places the legend in the lower-left corner of the axes.
• pos = 4 places the legend in the lower-right corner of the axes.

xlabel('string') labels the x-axis of the current axes.


ylabel(…) and zlabel(…) label the y-axis and z-axis, respectively, of the current axes.

text(x,y,'string') adds the string in quotes to the location specified by the point (x,y).
text(x,y,z,'string') adds the string in 3-D coordinates.
gtext('string') waits for you to press a mouse button or keyboard key while the pointer is within a
figure window. Pressing a mouse button or any key places 'string' on the plot at the selected
location.

For examples:
>> t = -pi:0.1:pi;
>> plot(t,sin(t),t,cos(t))
>> title('Function of Sine and Cosine','FontSize',18)
>> xlabel('t = -\pi to \pi','FontSize',16)
>> ylabel('sin(t) & cos(t)','Fontsize',16)
>> legend('Sine','Cosine')
>> text(-1,sin(-1),'sin(t)')
>> text(2,cos(2),'cos(t)')

Page 26
Including Symbols and Greek Letters in Text Strings
Text objects support a subset of TeX characters that enable you to use symbols in the title and axis
labels. For example, suppose you plot the function y = Ae −αt with A = 0.25 , α = 0.005 and t = 0
to 900.

>> t=0:900;
>> plot(t,0.25*exp(-0.005*t))
>> title('A{\ite}^{\alpha{\itt}}','FontSize',16)
>> ylabel('Amplitude','FontSize',16)
>> xlabel('Time \mu sec','FontSize',16)
>> text(300,0.25*exp(-0.005*300),...
'\bullet\leftarrow0.25{\ite}^{-0.005{\itt}} at {\itt} = 300','FontSize',14)

The following table lists these characters and the character sequence used to define them.

Character Sequence Symbol Character Sequence Symbol Character Sequence Symbol


\alpha \upsilon \sim ~
\beta \phi \leq
\gamma \chi \infty
\delta \psi \clubsuit
\epsilon \omega \diamondsuit
\zeta \Gamma \heartsuit
\eta \Delta \spadesuit
\theta \Theta \leftrightarrow
\vartheta \Lambda \leftarrow
\iota \Xi \uparrow

\kappa \Pi \rightarrow


\lambda \Sigma \downarrow

Page 27
\mu µ \Upsilon \circ º
\nu \Phi \pm ±
\xi \Psi \geq

\pi \Omega \propto


\rho \forall \partial
\sigma \exists \bullet •
\varsigma \ni \div ÷
\tau \cong \neq
\equiv \approx \aleph
\Im \Re \wp
\otimes \oplus \oslash
\cap \cup \supseteq
\supset \subseteq \subset
\int \in \o

\rfloor \lceil \nabla

\lfloor \cdot · \ldots ...

\perp \neg ¬ \prime ´


\wedge \times x \0
\rceil \surd \mid |

\vee \varpi \copyright ©


\langle \rangle

You can also specify stream modifiers that control the font used. The first four modifiers are
mutually exclusive. However, you can use \fontname in combination with one of the other
modifiers:
• \bf - bold font
• \it - italics font
• \sl - oblique font
• \rm - normal font
• \fontname{fontname} - specify the name of the font family to use.
• \fontsize{fontsize} - specify the font size on Font Units.

Stream modifiers remain in effect until the end of the string or only within the context defined by
braces {}.

Page 28
Axis Limits and Ticks
MATLAB selects axis limits based on the range of the plotted data. You can specify the limits
manually using the axis command. Call axis with the new limits defined as a four-element vector.

axis([xmin xmax ymin ymax]) sets the limits for the x and y-axis of the current axes.

For examples:

>> x = 0:.01:30;
>> subplot(211)
>> plot(x,x.*sin(x))
>> subplot(212)
>> plot(x,x.*sin(x))
>> axis([10 20 -20 20])

Axis also accepts a number of keywords for axes control:


Keywords Description
axis auto sets MATLAB to its default behavior of computing the current axes limits
automatically, based on the minimum and maximum values of x, y and z data.
axis tight sets the axis limits to the range of the data.
axis equal sets the aspect ratio so that the data units are the same in every direction.
axis square makes the current axes region square (cube when three-dimensional).
axis off turns off all axis lines, tick marks, and labels.
axis on turns on all axis lines, tick marks, and labels.

For example:
>> t = 0:0.01:2*pi;
>> subplot 221
>> plot(sin(t),cos(t))
>> subplot 222
>> plot(sin(t),cos(t))
>> axis equal
>> subplot 223
>> plot(sin(t),cos(t))
>> axis off
>> subplot 224
>> plot(sin(t),cos(t))
>> axis equal off

Page 29
MATLAB selects the tick mark locations based on the range of data so as to produce equally
spaced ticks (for linear graphs). You can specify different tick marks by setting the axes XTick and
YTick properties. Define tick marks as a vector of increasing values. The values do not need to be
equally spaced.

For examples:

>> t = 0:100;
>> plot(t,sin(t/100*2*pi));
>> set(gca,'XTick',0:5:100)

You can adjust the axis tick-mark locations and


the labels appearing at each tick mark.

>> labels = {'0',' ','10',' ','20',' ','30',' ',...


'40',' ','50',' ','60',' ','70',' ','80',' ',...
'90',' ','100'};
>> set(gca,'XTickLabel',labels)

>> temp = [21.1 22.2 19.4 23.3 23.9 21.1 20];


>> days = {'Sun','Mon','Tue','Wed','Thu','Fri','Sat'};
>> plot(1:7,temp)
>> axis([1 7 16 26])
>> set(gca,'XTickLabel',days)
>> grid
>> title('Temperature','FontSize',16)

4.3 Creating Specialized Plots


MATLAB supports a variety of graph types that enable you to present information effectively. The
type of graph you select depends, to a large extent, on the nature of your data. The following list
can help you to select the appropriate graph:
• Bar and area – graphs are useful to view results over time, comparing results, and displaying
individual contribution to a total amount.
• Pie charts – show individual contribution to a total amount.
• Histograms – show the distribution of data values.
• Compass – plots display direction and velocity vectors.

Page 30
Bar and Area graphs
Bar and area graphs display vector or matrix data. These types of graphs are useful for viewing
results over a period of time, comparing results from different datasets, and showing how
individual element contribute to an aggregate amount. Bar graphs are suitable for displaying
discrete data, whereas area graphs are more suitable for displaying continuous data.

bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups the bars produced by the
elements in each row.
bar(…,width) sets the relative bar width and controls the separation of bars within a group.
bar(…,'style') specifies the style of the bars. 'style' is 'group' or 'stack'. 'group' is the default mode
of display.
barh(…) creates a horizontal bars.
bar3(…) and bar3h(…) draw three-dimensional vertical and horizontal bar charts.

For examples:

>> Y = round(rand(5,3)*10);
>> subplot 221
>> bar(Y)
>> title('Group')
>> subplot 222
>> bar(Y,'stack')
>> title('Stack')
>> subplot 223
>> barh(Y,'stack')
>> title('Stack')
>> subplot 224
>> bar(Y,1.5)
>> title('Width = 1.5')

>> Y = cool(7);
>> subplot(2,2,1)
>> bar3(Y)
>> title('Default')
>> subplot(2,2,2)
>> bar3(Y,'group')
>> title('Group')
>> subplot(2,2,3)
>> bar3(Y,'stack')
>> title('Stack')
>> subplot(2,2,4)
>> bar3h(Y,'stack')
>> title('Stack-bar3')

Page 31
area(Y) plots the vector Y or the sum of each column in matrix Y.
area(X,Y) plots Y at the corresponding values of X.

For examples:
>> sales = [51.6 82.4 90.8 59.1 47];
>> x = 90:94;
>> profits = [19.3 34.2 61.4 50.5 29.4];
>> area(x,sales,'FaceColor',[.5 .9 .6],...
'EdgeColor','b','LineWidth',2)
>> hold on
>> area(x,profits,'FaceColor',[.9 .85 .7],...
'EdgeColor','y','LineWidth',2)
>> hold off
>> set(gca,'XTick',[90:94])
>> text(92,20,'Expenses')
>> text(91,60,'Profits')

Pie Charts
Pie charts display the percentage that each element in a vector or matrix contributes to the sum of
all elements.

pie(X) draws a pie chart using the data in X. Each element in X is represented as a slice in the pie
chart.
pie(X,explode) offsets a slice from the pie. explode is a vector or matrix of zeros and nonzeros that
correspond to X.
pie3(…) draws a three-dimensional pie chart.

For examples:

>> x = [1 3 0.5 2.5 2];


>> explode = [0 1 0 0 0];
>> subplot 221
>> pie(x)
>> title('2D-Default')
>> subplot 222
>> pie(x,explode)
>> title('2D-Explode')
>> subplot 223
>> pie3(x)
>> title('3D-Default')
>> subplot 224
>> pie3(x,explode)
>> title('3D-Default')

Page 32
Histograms
The hist function shows the
distribution of the elements in Y as a
histogram with equally spaced bins
between the minimum and
maximum values in Y. If Y is a
vector and is the only argument, hist
creates up to 10 bins.

For examples:
>> X = randn(10000,3);
>> subplot(2,1,1)
>> hist(X)
>> title('Histogram showing 10 bins')
>> subplot(2,1,2)
>> hist(X,20)
>> title('Histogram showing 20 bins')

Compass Plots
The compass function shows vectors emanating from the origin of a graph. The function takes
Cartesian coordinates and plots them on a circular grid.

compass(X,Y) displays a compass plot having n arrows, where n is the number of elements in X or
Y.
compass(Z) displays a compass plot having n arrows, where n is the number of elements in Z.

For example:

>> x = floor(randn(10,1)*10)
>> y = floor(randn(10,1)*10)
>> compass(x,y)

>>z = [-0.9+5i,-0.9-5i,2.6+3.2i,2.6-3.2i,3.4811,...
1.6+3.2i,1.6-3.2i,-4.3,-0.6+2.7i,-0.6-2.7i];
>> compass(z)

Page 33
5. Polynomials with MATLAB
5.1 Polynomial Operations
MATLAB represents polynomials as row vectors containing coefficients ordered by descending
powers. For example, consider the equation
p( x) = x 3 − 7 x + 6
This is the celebrated example Wallis used when he first represented Newton’s method to the
French Academy. To enter this polynomial into MATLAB, use
>> p = [1 0 –7 6];

Polynomial Roots
To calculate the roots of a polynomial given the coefficients, enter the coefficients in an array in
descending order. Be sure to include zeroes where appropriate.
>> r = roots(p)
r=
-3.0000
2.0000
1.0000
The roots function can find imaginary roots.
>> r2=roots([1 -6 18 -30 25])
r2 =
1.0000 + 2.0000i
1.0000 - 2.0000i
2.0000 + 1.0000i
2.0000 - 1.0000i

Characteristic Polynomials
The poly function also computes the polynomial with specified roots.

p = poly(r) where r is vector returns a row vector whose elements are the coefficients of the
polynomial whose roots are the elements of r.
>> r = [-4 -2 -1 1];
>> p = poly(r)
p=
1 6 7 -6 -8

p=poly(A) where A is an n-by-n matrix returns an n+1 element row vector whose elements are the
coefficients of the characteristic polynomial.
det(λΙ − A) = c1λn + ... + c n λ + c n +1
>> A=[1.2 3 -0.9;5 1.75 6;9 0 1];
>> poly(A)
ans =
1.0000 -3.9500 -1.8500 -163.2750

Page 34
Polynomial Evaluation
The polyval function evaluates a polynomial at a specified value. To evaluate p at x = 3, use
>> p = [1 1 -2 3];
>> polyval(p,3)
ans =
33
p( x) = x 3 + x 2 − 2 x + 3
p (3) = 33 + 3 2 − 2(3) + 3 = 33

The polyval function also works as an


element-wise across a vector of points,
returning the vector where each element is the
value of the polynomial at the corresponding
element of the input vector:
>> x = -5:0.1:5;
>> y = polyval(p,x);
>> plot(x,y)
>> grid

Convolution and Deconvolution


Polynomial multiplication and division correspond to the operations convolution and deconvolution.
The functions conv and deconv implement these operations.

w = conv(u,v) convolves vectors u and v. Consider the polynomials u ( s ) = s 2 + 2 s + 3 and


v( s ) = 4 s 2 + 5s + 6 . To compute their product,
>> u = [1 2 3];
>> v = [4 5 6];
>> w = conv(u,v)
w=
4 13 28 27 18

[q,r] = deconv(v,u) deconvolves vector u out of vector v, using long division. The quotient is
returned in vector q and the remainder in vector r such that v = conv(u,q)+r.
>> [q,r] = deconv(w,v)
q=
1 2 3
r=
0 0 0 0 0

Page 35
Partial Fraction Expansion
residue finds the partial fraction expansion of the ration of two polynomials. This is particularly
useful for applications that represent systems in transfer function form. For polynomials b and a, if
there are no multiple roots.
b( s ) r r r
= 1 + 2 + ... + n + k s
a( s) s − p1 s − p 2 s − pn

where r is a column vector of residues, p is a column vector of pole locations, and k is a row vector
of direct terms. Consider the transfer function

4 s 2 − 40s + 98
s 3 − 15s 2 + 74s − 120

>> b=[4 -40 98];


>> a=[1 -15 74 -120];
>> [r,p,k]=residue(b,a)
r=
1.0000
2.0000
1.0000
p=
6.0000
5.0000
4.0000
k=
[]

The result can be expressed as

4 s 2 − 40s + 98 1 2 1
= + +
s − 15s + 74s − 120 s − 6 s − 5 s − 4
3 2

Given three input arguments (r, p and k), residue converts back to polynomial form
>> [b2,a2]=residue(r,p,k)
b2 =
4.0000 -40.0000 98.0000
a2 =
1.0000 -15.0000 74.0000 -120.0000

Page 36
5.2 Data Analysis and Curve Fitting
In numerous applications, we are faced with the task of describing data, which has been
experimentally measured with analytical functions. In curve fitting, one seeks to find some smooth
curve that “best fits” the data. Best fit is interpreted as minimizing the sums of the squared errors at
the data points. In these notes, we limit our discussion to the use of the MATLAB function polyfit,
which finds the coefficients of a polynomial that best fits a set of data, in the least-squares sense.
The format of the function is:
>> eqn = polyfit(X,Y,N)
where:
X,Y are column vectors, of the same length, which contain the data
N is the order of the polynomial

MATLAB finds the coefficients of a polynomial P(X) of degree N that fits the data, P(X(i))~=Y(i),
in a least-squares sense.
Use of the function polyfit is best illustrated through examples:

Linear

>> x=0.1:0.1:10;
>> y=5+1.5*x;
>> y1=y+randn(1,100);
>> plot(x,y1,'*')

Let’s assume that we have collected the above


data and that we want to fit them. Clearly the
data follows a linear pattern, so we can use:
>> eqn=polyfit(x,y1,1)
eqn =
1.4705 5.3344
these are the coefficients of the polynomial. So according to our fit, the data can be described by
the polynomial:
y1 = 1.4705 x + 5.3344
We can reconstruct the best-fit polynomial by
using:
>> y2=polyval(eqn,x);
>> plot(x,yn,'x',x,y2,'m')
>> legend('data','fit')

Page 37
Non-linear
Similarly, we can try to fit non-linear data with
higher order polynomials.

>> x = 0:0.2:1.4;
>> y = cos(x);
>> plot(x,y,'x')

>> eqn1 = polyfit(x,y,2)


eqn1 =
-0.3664 -0.0924 1.0081
>> x1 = 0:0.01:1.4;
>> y1 = polyval(eqn1,x1);
>> hold on
>> line1 = plot(x1,y1,'g');

>> delete(line1)
>> eqn2=polyfit(x,y,3)
eqn2 =
0.1040 -0.5848 0.0220 0.9994
>> y2=polyval(eqn2,x1);
>> line2=plot(x1,y2,'m');

Page 38
6. 3-D Visualization
6.1 Line plots of 3D data
The 3-D analog of the plot function is plot3. If x, y, and z are three vectors of the same length,
plot3(x,y,z)
generates a line in 3-D through the points whose
coordinates are the elements of x, y, and z and then
produces a 2-D projection of that line on the screen. For
example,
>> t= -3*pi:0.1:3*pi;
>> plot3(t,sin(t),cos(t))
>> grid on

A different view can be achieved with the function view

>> view([1,0,0]) >> view([0,1,0]) >> view([0,0,1])

6.2 Preparing data


MATLAB defines a surface by the z coordinates of points above a rectangular grid in the x-y plane.
The meshgrid function transforms the domain specified by two vectors x and y into matrices, X
and Y.
[X,Y] = meshgrid(x,y) 3
[X,Y] = meshgrid(x)
[X,Y,Z] = meshgrid(x,y,z)
2

For example,
>> [X,Y]=meshgrid(-2:2) 1

X=
-2 -1 0 1 2 0
-2 -1 0 1 2
-2 -1 0 1 2
-1
-2 -1 0 1 2
-2 -1 0 1 2
-2
Y=
-2 -2 -2 -2 -2
-1 -1 -1 -1 -1 -3
-3 -2 -1 0 1 2 3
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
>> plot(X,Y,‘rx’), axis([-3 3 –3 3])

Page 39
sin( X 2 + Y 2 )
Then we can graph the function f ( X , Y ) = :
X 2 +Y2
>> Z=sin(sqrt(X.^2+Y.^2)+eps)./(sqrt(X.^2+Y.^2)+eps);
>> mesh(X,Y,Z)

The first command creates a matrix whose


entries are the points of a grid in the square -
2 <= X <= 2, -2 <= Y <= 2. The small
squares that make up the grid are 0.2 units
wide and 0.2 units tall. The second
command creates a matrix whose entries are
the values of the function f ( X , Y ) at the
grid points. The third command uses this
information to construct the graph. You can
increase the density of (X,Y) points to give a
figure showing more detail.

>> [X,Y]=meshgrid(-2:.2:2);
>> Z=sin(sqrt(X.^2+Y.^2)+0.0001)./(sqrt(X.^2+Y.^2)+0.0001);
>> mesh(X,Y,Z)

6.3 Contour, Mesh and Surface Plots


Contour, Contourf, Contourc and Contour3 Plots
contour, contourf and contour3 plots displays 2-D and 3-D isolines of matrix Z.

contour(Z) draws a contour plot of matrix Z, where Z is interpreted as heights with respect to the
x-y plane.
contour(Z,n) draws a contour plot of matrix Z with n contour levels.
contour(X,Y,Z) and contour(X,Y,Z,n) draw contour plots of Z. X and Y specify the x and y axis
limits, n is contour levels.
[C,h] = contour(…) returns the contour matrix C and a vector of handles to graphics objects.
clabel(C,h) rotates the labels and inserts them in the contour lines.
contourf (…) filled two-dimensional contour plot
contour3(…) creates a three-dimensional contour plot of a surface defined on a rectangular grid.

Page 40
For example:

>> [X,Y]=meshgrid(-2:.2:2);
>> Z=sin(X).*sin(Y).*exp(-X.^2-Y.^2);
>> contour(X,Y,Z,10)

>> [X,Y]=meshgrid(-2:.2:2);
>> Z=sin(X).*sin(Y).*exp(-X.^2-Y.^2);
>> [C,h]=contour(X,Y,Z,10);
>> clabel(C,h)

>> [X,Y]=meshgrid(-2:.2:2);
>> Z=sin(X).*sin(Y).*exp(-X.^2-Y.^2);
>> contourf(X,Y,Z,20)

>> [X,Y]=meshgrid(-2:.2:2);
>> Z=sin(X).*sin(Y).*exp(-X.^2-Y.^2);
>> [C,h]=contour3(X,Y,Z,20);
>> set(h,'LineWidth',2)

Page 41
Mesh, Meshc and Meshz Plots
mesh, meshc and meshz create wire frame parametric surfaces specified by X, Y and Z.

mesh(Z) draws a wire frame mesh using X = 1:n and Y = 1:m, where [m,n] = size(Z). The height Z
is a single-valued function defined over a rectangular grid. Colour is proportional to surface height.
mesh(X,Y,Z) draws a wire frame mesh with colour determined by Z, so colour is proportional to
surface height. X and Y are the intersections of the wire frame grid lines.
meshc(…) draws a contour plot beneath the mesh.
meshz(…) draws a curtain plot around the mesh.

For example:

>> [X,Y] = meshgrid(-8:.5:8);


>> r = sqrt(X.^2+Y.^2)+0.0001;
>> Z = sin(r)./(r);
>> mesh(X,Y,Z)

>> [X,Y,Z]=peaks(30);
>> meshc(X,Y,Z)

>> [X,Y]=meshgrid(-2:.2:2);
>> Z=X.*exp(-X.^2-Y.^2);
>> meshz(X,Y,Z)

Page 42
Surf and Surfc Plots

surf(Z) creates a three-dimensional shaded surface from the z components in matrix Z. The height
Z is a single-valued function defined over a geometrically rectangular grid. Z specifies the colour
data as well as the surface height, so the colour is proportional to the surface height.
surf(X,Y,Z) creates a shaded surface using Z for the colour data as well as surface height. X and Y
are vectors or matrices defining the x and y components of a surface.
surfc(…) draws a contour plot beneath the surface.

For example:

>> [X,Y]=meshgrid(-2:.1:2);
>> Z=sin(X).*sin(Y).*exp(-X.^2-Y.^2);
>> surf(X,Y,Z)

>> Z=membrane;
>> surfc(X,Y,Z)
>> colormap cool

Page 43
6.4 Colormap
Each MATLAB figure window has a colormap associated with it. A colormap is simply a three-
column matrix whose length is equal to the number of the colours it defines. Each row of the
matrix defines a particular colour by specifying three values in the range 0 to 1. These values
define the RGB components.
This table lists some representative RGB colour definitions:
Red Green Blue Color
0 0 0 black
0 0 1 blue
0 1 0 green
0 1 1 cyan
1 0 0 red
1 0 1 magenta
1 1 0 yellow
1 1 1 white
0.5 0 0 dark red
0.5 0.5 0.5 grey
0.5 1 0.8 aquamarine
1 0.6 0.4 copper

colormap(map) sets the colormap to the matrix map.


colormap(‘default’) sets the current colormap to the default colormap.

You can create colormaps with MATLAB’s array operations or you can use any of several
functions that generate useful maps, including:

hsv - Hue-saturation-value color map.


hot - Black-red-yellow-white color map.
gray - Linear gray-scale color map.
bone - Gray-scale with tinge of blue color map.
copper - Linear copper-tone color map.
pink - Pastel shades of pink color map.
white - All white color map.
flag - Alternating red, white, blue, and black color map.
lines - Color map with the line colors.
colorcube - Enhanced color-cube color map.
jet - Variant of HSV.
prism - Prism color map.
cool - Shades of cyan and magenta color map.
autumn - Shades of red and yellow color map.
spring - Shades of magenta and yellow color map.
winter - Shades of blue and green color map.
summer - Shades of green and yellow color map.

You can add a color bar to figure windows .


colorbar adds a new vertical colorbar on the right side of the current axes.
colorbar(‘horiz’) add a new horizontal colorbar on the bottom of the current axes.
colorbar(‘off’) delete all colorbar

Page 44
For examples:

>> [X,Y]=meshgrid(-2:0.2:2);
>> Z=X.*exp(-X.^2-Y.^2);
>> surf(X,Y,Z,’linestyle’,’none’)
>> colormap hot
>> colorbar

>> [X,Y]=meshgrid(-2:0.2:2);
>> Z=X.*exp(-X.^2-Y.^2);
>> surf(X,Y,Z,X)
>> xlabel('X axis','FontSize',14)
>> ylabel('Y axis','FontSize',14)
>> zlabel('Z axis','FontSize',14)
>> colormap(winter)
>> colorbar('horiz')

>> [X,Y]=meshgrid(-2:0.2:2);
>> Z=X.*exp(-X.^2-Y.^2);
>> surf(X,Y,Z,Y)
>> axis([-3,3,-3,3,-0.6,0.6])
>> colormap('default')
>> colorbar

Page 45
7. File I/O Function
7.1 Open and Close file
The type of file I/O involves C-style I/O functions. These functions give the user a great deal of
flexibility to read and write files in various formats. The first step to use these functions is to open
the desired file using the fopen command,
>> fid = fopen(name, mode)

where name is the name of the desired file and mode is one of the following:

mode Description
'r' Open file for reading (default).
'w' Open file, or create new file, for writing; discard existing contents, if any.
'a' Open file, or create new file, for writing; append data to the end of the file.
'r+' Open file for reading and writing.
'w+' Open file, or create a new file, for reading and writing; discard existing contents, if any.
'a+' Open file, or create new file, for reading and writing; append data to the end of the file.
To open in text mode, add 't' to the permission string, for example 'rt' and 'wt+'.

The fopen function returns a file descriptor that is needed by the file functions that perform the
actual reading and writing. To close an opened file after all readings and/or making modifications,
use the fclose function with the file descriptor as its argument, fclose(fid). The two files that are
always opened and never need to be closed are standard output (file descriptor 1) and standard error
(file descriptor 2).

7.2 Written file


There are two types of I/O in MATLAB, formatted I/O and binary I/O. Formatted output is written
by one of the two functions,
>> fprintf(fid,template,...)
>> sprintf(template,...)

depending on where the user intends to send the output. fprintf sends the output to a file with file
descriptor fid, and sprintf formats the output as a string.
The form of the template is a string that may include ordinary characters, which are written to the
output stream as-is, and conversion specifications, which begin with the character %. What
conversion specifies include:

MALAB Output Conversion Specifies


%d, %i Print an integer as a signed decimal number. These are synonymous for output,
but are different when used with scanf of input.
%o Print an integer as an unsigned octal number.
%u Print an integer as an unsigned decimal number.
%x, %X Print an integer as an unsigned hexadecimal number. %x uses lower-case letters
and %X user upper-case.
%f Print a floating-point number in normal (fixed-point) notation.
%e, %E Print a floating-point number in exponential notation. %e used lower-case letters
and %E user upper-case.
%g, %G Print a floating-point number in either normal (fixed-point) or exponential

Page 46
notation, whichever is more appropriate for its magnitude. %g uses lower-case
letters and %G uses upper-case.
%c Print a single character.
%s Print a string
%% Print a literal ‘%’ character.

A format modifier may also be given between the '%' and the conversion character to specify a flag
for justification, a minimum field width, and (optional) precision in the form, flag width precision.
For example,

>> p = .052;n = 100;fname = 'output.txt';


>> fprintf(1,'The sample size is %d\nwith a %5.1f%% defective rate.\n',n,100*p);
>> fprintf(1,'The data is stored in %s.\n',fname);

Create a text file called ‘sin.txt’ containing a short table of the sine function:
>> x=0:360;
>> y=[x;sin(x*pi/180)];
>> fid=fopen('sin.txt','wt');
>> fprintf(fid,'%6.2f %12.8f \n',y);
>> fclose(fid);

7.3 Read File


Formatted input is obtained using fscanf, or sscanf. These functions have a template argument
similar to the output functions, but have an optional argument size instead of a list of objects to
print,
>> A = fscanf(fid,format,size)
>> A = sscanf(fid,format,size)

reads the amount of data specified by size, converts it according to the specified format string,
and returns it along with a count of elements successfully read. Size is an argument that
determines how much data is read. Valid options are:
n Read n elements into a column vector.
inf Read to the end of the file, resulting in a column vector containing the same
number of elements as it is in the file.
[m,n] Read enough elements to fill an m-by-n matrix, filling the matrix in column
order. n can be Inf, but not m.

The format string consists of ordinary characters and/or conversion specifications. Conversion
specifications indicate the type of data to be matched and involve the character %, optional width
fields, and conversion characters, organized as shown below:

Valid conversion characters are:


%c Sequence of characters; number specified by field width
%d Decimal numbers
%e,%f,%g Floating-point numbers
%i Signed integer
%o Signed octal integer

Page 47
%s A series of non-white-space characters
%u Signed decimal integer
%x Signed hexadecimal integer
[...] Sequence of characters (scanlist)

For example:

>> fid=fopen('earth.txt','r');
>> s=fscanf(fid,'%f %f',[2 inf]);
>> fclose(fid);
>> plot(s(1,:),s(2,:),'.');

Page 48
8. M-file Programming
MATLAB provides two ways to package sequences of MATLAB commands:
‰ Script M-files
‰ Function M-files
These two categories of M-files differ in two important respects:
Script M-files Function M-files
Do not accept input arguments nor return output Can accept input arguments and return output
arguments arguments
Operate on data in the workspace Internal variables are local to the function by
default
Useful for automating a series of steps you need Useful for extending the MATLAB language for
to perform many times. your application

Create M-file:
Choose New from the File menu and select M-file. Or type “edit” command in the Command
Window.

Save M-file:
Simply go to the File menu and choose Save (remember to save it with the ‘.m’ extension).

Open M-file:
Simply go to the File menu and choose Open.

Run the M-file:


After the m-file is saved with the name filename.m in the MATLAB folder or directory, you can
execute the commands in the m-file by simply typing filename at the MATLAB prompt.

8.1 Scripts
Scripts are collections of MATLAB commands stored in plain text files. When you type the name
of the script file at the MATLAB prompt, the commands in the script file are executed as if you
input the directly.

Simple Script Example: Try entering the following commands in an M-file and save them to
script_test.m.

% Script M-file
% This program shows how to use the script file.
start_th=0;
end_th=2*pi;
th=start_th:.1:end_th;
x=sin(th);
y=cos(th);
plot(x,y);
axis equal
title('Sine Vs. Cosine','FontSize',18)
xlabel('Sine','FontSize',16)
ylabel('Cosine','FontSize',16)

Page 49
This file is now a MATLAB script. Typing
script_test at the command window executes
the statements in the script.

>> script_test

8.2 Functions
MATLAB functions are similar to C functions. It is stored as plain text in files having names that
ended with the extension “.m”. These files are called, not surprisingly, M-files. Each M-file
contains exactly one MATLAB function. Thus, a collection of MATLAB functions can lead to a
large number of relatively small files.

Simple Function Example: Try entering the following commands in an M-file and save to
triangle_area.m.

function x=triangle_area(a,b,c)

% Function M-file
% x=triangle_area(a,b,c)
% Given a triangle with side lengths a,b and c,
% its area can be computed and return to x.

s=1/2*(a+b+c);
x=sqrt(s*(s-a)*(s-b)*(s-c));

The triangle_area function accepts three input arguments and returns a single output argument. To
call the triangle_area function, enter:
>> triangle_area(3,4,5)
ans =
6
>> area=triangle_area(6,8,10)
area =
24

The function definition line informs MATLAB that the M-file contains a function, and specifies the
argument calling sequence of the function. The function definition line for the triangle_area
function is:
function x = triangle_area(a,b,c)
keyword input argument
output argument function name

Page 50
8.3 Flow Control
There are four flow control statements in MATLAB:
• if statements
• switch statements
• while loops
• for loops

if statements and while loops use relational or logical operation to determine what steps to perform
in the solution of a problem. The relational operators in MATLAB for comparing two matrices of
equal size are shown in following:
Relational Operators Meaning
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal to
~= not equal to
When the relational operators are used, a comparison is done between the pairs of corresponding
elements. The result is a matrix of 1 and 0, which 1 representing TRUE and 0 representing FALSE.
For example:
>> a=[1 2 4 6 2];
>> b=[2 1 4 5 2];
>> a= =b
ans =
0 0 1 0 1
>> a>b
ans =
0 1 0 1 0

There are four logical operators in MATLAB. These are shown in following:

Logical Operator Meaning


~ Not
& And
| Or
xor Exclusive or
The symbols ~, &, | are the logical operators AND, OR, and NOT. They work element-wise on
matrices, with 0 representing FALSE and anything nonzero representing TRUE. X & Y does a
logical AND, X | Y does a logical OR, and ~X complements the elements of X. The function
xor(X,Y) implements the exclusive OR operation.

Input Not And Or Xor


X Y ~X X&Y X|Y xor(X,Y)
0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 1 0

Page 51
if, elseif and else
The if statement evaluates a logical expression and executes a group of statements when the
expression is TRUE. Its syntax is

if condition
statements
end

The optional elseif and else keywords provide for the execution of alternate groups of statements. A
keyword end, which matches the if, terminates the last group of statements. Its syntax is

if condition
statements
elseif condition
statements
elseif condition
statements
.
.
.
else
statements
end

For example, open the ‘triangle_area.m’ M-file and add the command as follows:
function x=triangle_area(a,b,c)

% Function M-file
% x=triangle_area(a,b,c)
% Given a triangle with side lengths a,b and c,
% its area can be computed and return to x.

if a<0 | b<0 | c<0


error('Input a,b,c must be are positive.')
elseif (a+b)<c | (a+c)<b | (b+c)<a
warning('The sum of any two side lengths must be greater than the third side length.')
else
s=1/2*(a+b+c);
x=sqrt(s*(s-a)*(s-b)*(s-c));
end

Page 52
switch and case
The switch statement executes groups of statements based on the value of a variable or expression.
The keywords case and otherwise delineate the groups. Only the first matching case is executed.
There must always be an end to match the switch. Its syntax is:

switch expression
case value1
statements
case value2
statements
.
.
.
otherwise
statements
end

Example with script:


n=input('Please input number:');
x=sign(n);
switch x
case -1
disp('The input number is negative.')
case 0
disp('The input number is zero.')
case 1
disp('The input number is positive.')
end

while
The while loop repeats a group of statements and indefinite number of times under control of a
logical condition. A matching end delineates the statements. Its syntax is:

while expression
statements
end

Example with function:


function sum=while_test(x,y)

sum=0;
while x<=y
sum=sum+x;
x=x+1;
end

Page 53
for
The for loop repeats a group of statements a fixed, predetermined number of times. A matching
end delineates the statements.

for index=initialisation : increment : end


statements
end

Example with function:


function matrix=for_test(x,y)

for i=1:x
for j=1:y
matrix(i,j)=i*j;
end
end

Page 54
9. Creating Graphical User Interfaces
9.1 GUI with MATLAB
A graphical user interface (GUI) is a user interface built with graphical objects, such as buttons,
text fields, sliders, and menus. Applications that provide GUIs are generally easier to learn and use
since the person using the application does not need to know what commands are available or how
they work. The action that results from a particular user action can be made clear by the design of
the interface.

Display Message box

msgbox(message):
Creates a message box that automatically wraps message to fit an appropriately sized figure.
Message is a string vector, string matrix, or cell array. For example,
>> msgbox('Hello World!!')

msgbox(message,title):
Specifies the title of the message box. For example,
>> msgbox('Hello World!!','Test')

msgbox(message,title,'icon'):
Specifies which icon to be displayed in the message box. 'icon' is 'none', 'error', 'help', or
'warn'. The default is 'none'. For example,
>> msgbox('Input must be positive!!!','Error','error')

>> msgbox('Input must be positive!!!','Error','warn')

>> msgbox('Input must be positive!!!','Error','help')

Other commands of message boxes are errordlg, helpdlg, warndlg, inputdlg, and questdlg.

Page 55
inputdlg example with script file:
inputdlg syntax: answer = inputdlg(Prompt,Title,LineNo,DefAns)
• Prompt is a cell array containing prompt strings.
• Title specifies a title for the dialog box.
• LineNo specifies the number of lines for each user to enter value.
• DefAns specifies the default value to display for each prompt.

prompt={'Input function:','Input color:','Input Limit:'};


title='Plot function';
lines=1;
defans={'sin(x)','r','2*pi'};
answers=inputdlg(prompt,title,lines,defans);
x=0:0.1:str2num(answers{3});
y=eval(answers{1});
figure;
plot(x,y,answers{2});

questdlg example:
Syntax: answer=questdlg(Question,Title,Btn1,Btn2,Btn3,Default);
• Question is a cell array or a string that automatically wraps to fit within the dialog box.
• Title specifies a title for the dialog box.
• Btn1, Btn2, and Btn3 is three push buttons labels.
• Default specifies the default button selection and must be Btn1, Btn2, or Btn3.

>> question='Do you want to continue?';


>> answer=questdlg(question,'Game Over','Yes','No','Help','Yes');

Page 56
GUIDE – GUI Development Environment

GUIDE provides a set of tools for laying out your GUI. The Layout Editor is the control panel for
GUIDE. To start the Layout Editor, use the guide command or choose New from the File menu ,
select GUI. This command display the GUIDE Quick Start dialog box.

After select the Blank GUI, the following figure shows the Layout Editor:

Page 57
Alignment Tool: adds and arranges objects in the figure window.
Menu Editor: creates menus for the window menu bar and context menus for any
component in your layout.
Property Inspector: inspects and sets property values.
Object Browser: observes a hierarchical list of the Handle Graphics objects in the current
MATLAB session.
Run: save and run current GUI.
Component Palette: contains the user interface controls that you can use in your GUI. These
components are MATLAB uicontrol objects and are programmable via their
Callback properties, which are shown in following:

Push Buttons generate an action when pressed.


Sliders accept numeric input within a specific range by enabling the user
to move a sliding bar.
Radio Buttons similar to checkboxes, but are intended to be mutually exclusive
within a group of related radio buttons.
Check Boxes generate an action when clicked and indicate their status as
checked or not checked.
Edit Texts fields that enable users to enter or modify text strings.
Static Texts controls displays lines of text.
Popup Menus open to display a list of choices when users press the arrow.
List Boxes display a list of items and enable users to select one or more items.
Toggle Buttons generate an action and indicate a binary state.
Tables create a table component.
Axes enable your GUI to display graphics.
Panels organize GUI components into groups.
Button Groups organize radio buttons and toggle buttons into groups.
ActiveX Control Display ActiveX controls in current GUI.

Page 58
9.2 Programming GUIs
Example 1:

1. Open the Layout Editor using the guide


command
2. Choose Grid and Rulers from the Tools menu,
select all checkboxes and set the Grid Size to 30

3. Click the ‘Static Text’


button at the ‘Component
Palette’.

4. Set the size of the control by clicking on the layout area and then dragging the cursor to the
lower-right corner before releasing the mouse button. Double click on the box just created
and the Property Inspector will pop up. Set the type in String to ‘x :’. The String will be
displayed in the ‘Static Text’ now.

Page 59
5. Same as the above, add six static texts, six edit texts, two push buttons and one axes.
Arrange them as shown in the following picture.

6. Set Properties for Each Component,


Static Texts: set up the string only to create the labels ‘x :’, ‘y :’, ‘Degree of equation :’, ‘x
label :’, ‘y label :’, ‘The equation is :’ by ascending.
Edit texts: set up all strings to empty.
set up the tag to ‘input_x’, ’input_y’, ’degree’, ’xlabel’, ’ylabel’ and
‘equation’ by ascending.
set up the backgroundcolor to white.
Push buttons: set up the string to ‘Close’ and ‘Submit’.
set up the callback for Close button to command ‘close’.
set up the Tag for Submit button to ‘submit’.
7. Choose GUI Options.. from the Tools menu, change the Command-line accessibility to
‘On (GUI may become Current Figure from Command Line)’.
8. Save the GUI editor and name it “labreport”. GUIDE will create two files ‘labreport.fig’
and ‘labreport.m’ as same time.
9. Open the file ‘labreport.m’, find the function “submit_Callback”, it is the call back function
when you press the Submit button. Write the program as follows:

%--- Executes on button press in submit.


function submit_Callback(hObject, eventdata, handles)
% hObject handle to submit (see GCBO)
% eventdata reserved – to be defined in a future version of MATLAB.
% handles structure with handles and user data (see GUIDATA)

Page 60
x=str2num(get(handles.input_x,'String'));
y=str2num(get(handles.input_y,'String'));
degree=str2num(get(handles.degree,'String'));
xlab=get(handles.xlabel,'String');
ylab=get(handles.ylabel,'String');

if length(x)~=length(y)
warndlg('Number of x and y not equal!');
end

eqn=polyfit(x,y,degree);
plotx=linspace(x(1),x(length(x)),100);
ploty=polyval(eqn,plotx);

eqn=char(poly2sym(eqn))

set(handles.equation,'String',eqn)

plot(x,y,'x');
hold on
plot(plotx,ploty,'g');
xlabel(xlab);
ylabel(ylab);
legend('Input Data','Equation');
hold off

10. Finally, activate the figure by selecting the Run item in the Tools menu or by clicking the
Run Figure in the toolbar.

Page 61
Example2:
1. Open the Layout Editor using the guide command.
2. Add static texts, edit texts, push buttons, popup menu and axes. Arrange them as shown in
the following picture.

3. Set property for popup menu, change the


‘Tag’ to popup and make sure each item in
the popup menu list is on a separate line in
the String property edit box:

Page 62
4. Set Properties for other Component,
Static Texts: set up the string to create the labels.
Edit texts: set up the string to create the labels.
set up the tag to ‘A’, ’B’, ’C’, ’TR1’, ’TR2’ and ‘DR’ correspondingly.
Push buttons: set up the string to ‘Calculation’ and ‘Close’.
set up the callback for Close button to command ‘close’.
set up the callback for Calculation button to ‘quad’.
5. Select “Tools – GUI Options..”, change the Command-line accessibility to ‘On (GUI may
become Current Figure from Command Line)’.
6. Save the GUI editor and name it “gui_quad”.
7. Create the new file quad.m that will perform the calculations and give the results as follows:

clear;
hh=findobj(gcf,'Tag','A');
a=str2num(get(hh,'String'));
hh=findobj(gcf,'Tag','B');
b=str2num(get(hh,'String'));
hh=findobj(gcf,'Tag','C');
c=str2num(get(hh,'String'));
hh=findobj(gcf,'Tag','popup');
val=get(hh,'Value');

eqn=[a b c];
root=roots(eqn);
color='gbcmyk';
hh(1)=findobj(gcf,'Tag','DR');
hh(2)=findobj(gcf,'Tag','TR1');
hh(3)=findobj(gcf,'Tag','TR2');
set(hh,'String','No result')
cla
if (b^2-4*a*c)>=0
root=real(root);
if diff(root)==0
set(hh(1),'String',num2str(root(1)))
else
set(hh(2),'String',num2str(root(1)))
set(hh(3),'String',num2str(root(2)))
end
x=linspace(min(root)-10,max(root)+10,100);
y=polyval(eqn,x);
plot(x,y,color(val),x([1 end]),[0 0],'r:')
else
errordlg('No real root exist!','Complex Root Problem!')
end

Page 63
10. Some MATLAB function descriptions
General Purpose Commands
help Display M-file help for MATLAB functions in the Command Window
clear Remove items from the workspace
disp Display text or array
length Length of vector
size Array dimensions
who, whos List the variables in the workspace
clc Clear Command Window
delete Delete files or graphics objects
exit Terminate MATLAB
format Control the display format for output
edit Edit an M-file

File I/O Functions


fclose Close one or more open files
fopen Open a file or obtain information about open files

fprintf Write formatted data to file


fscanf Read formatted data from file

Elementary Matrices and Matrix Manipulation


eye Identity matrix
linspace Generate linearly spaced vectors
logspace Generate logarithmically spaced vectors
ones Create an array of all ones
rand Uniformly distributed random numbers and arrays
randn Normally distributed random numbers and arrays
zeros Create an array of all zeros
: (colon) Regularly spaced vector
i Imaginary unit
j Imaginary unit
inf Infinity
pi Ratio of a circle's circumference to its diameter,

Page 64
Elementary Math Functions
abs Absolute value and complex magnitude
acos, acosh Inverse cosine and inverse hyperbolic cosine in radians

acosd Inverse cosine in degree


acot, acoth Inverse cotangent and inverse hyperbolic cotangent in radians
acotd Inverse cotangent in degree
acsc, acsch Inverse cosecant and inverse hyperbolic cosecant in radians
angle Phase angle
asec, asech Inverse secant and inverse hyperbolic secant in radians
asin, asinh Inverse sine and inverse hyperbolic sine in radians
atan, atanh Inverse tangent and inverse hyperbolic tangent in radians
atan2 Four-quadrant inverse tangent in radians
ceil Round toward infinity
cos, cosh Cosine and hyperbolic cosine in radians
cosd Cosine of argument in degree
cot, coth Cotangent and hyperbolic cotangent in radians
cotd Cotangent of argument in degree
csc, csch Cosecant and hyperbolic cosecant in radians
exp Exponential
fix Round towards zero
floor Round towards minus infinity
gcd Greatest common divisor
imag Imaginary part of a complex number
lcm Least common multiple
log Natural logarithm
log2 Base 2 logarithm and dissect floating-point numbers into exponent and
mantissa
log10 Common (base 10) logarithm
mod Modulus (signed remainder after division)
real Real part of complex number
rem Remainder after division
round Round to nearest integer
rat, rats Rational fraction approximation
factorial Factorial function
sec, sech Secant and hyperbolic secant in radians
secd Secant of argument in degree
sign Signum function
sin, sinh Sine and hyperbolic sine in radians
sind Sine of argument in degree
sqrt Square root
tan, tanh Tangent and hyperbolic tangent in radians

Page 65
tand Tangent of argument in degree

Matrix Functions - Numerical Linear Algebra


det Matrix determinant
norm Vector and matrix norms
inv Matrix inverse

Data Analysis and Fourier Transform Functions


factor Prime factors
max Maximum elements of an array
mean Average or mean value of arrays
median Median value of arrays
min Minimum elements of an array
primes Generate list of prime numbers
prod Product of array elements
cumprod Cumulative product
sort Sort elements in ascending order
sortrows Sort rows in ascending order
std Standard deviation
sum Sum of array elements
cumsum Cumulative sum
diff Differences and approximate derivatives

Polynomial and Interpolation Functions


poly Polynomial with specified roots
polyfit Polynomial curve fitting
polyval Polynomial evaluation
roots Polynomial roots
conv Convolution and polynomial multiplication
deconv Deconvolution and polynomial division
residue Convert between partial fraction expansion and polynomial roots

Function Functions - Nonlinear Numerical Methods


fzero Find zero of a function of one variable
quad Numerical evaluation of integrals, adaptive Simpson quadrature

Plotting and Data Visualization


bar Vertical bar chart
barh Horizontal bar chart
hist Plot histograms
histc Histogram count
hold Hold current graph

Page 66
loglog Plot using log-log scales
pie Pie plot
plot Plot vectors or matrices.
polar Polar coordinate plot
semilogx Semi-log scale plot
semilogy Semi-log scale plot
subplot Create axes in tiled positions
bar3 Vertical 3-D bar chart
bar3h Horizontal 3-D bar chart
plot3 Plot lines and points in 3-D space
clabel Add contour labels to a contour plot
grid Grid lines for 2-D and 3-D plots
legend Graph legend for lines and patches
title Titles for 2-D and 3-D plots
xlabel X-axis labels for 2-D and 3-D plots
ylabel Y-axis labels for 2-D and 3-D plots
zlabel Z-axis labels for 3-D plots
contour Contour (level curves) plot
contourc Contour computation
meshc Combination mesh/contourplot
mesh 3-D mesh with reference plane
peaks A sample function of two variables
surf 3-D shaded surface graph
surfc Combination surf/contourplot
area Area plot
compass Compass plot
ezplot Easy to use function plotter
ezplot3 Easy to use 3-D parametric curve plotter
ezpolar Easy to use polar coordinate plotter
ezsurf Easy to use 3-D colored surface plotter
ezsurfc Easy to use combination surface/contour plotter
fill Draw filled 2-D polygons
fplot Plot a function
pie3 3-D pie plot
colorbar Display color bar (color scale)
colormap Set the color look-up table (list of colormaps)
axes Create Axes object
figure Create Figure (graph) windows
line Create Line object (3-D polylines)
clf Clear figure
close Close specified window

Page 67
axis Plot axis scaling and appearance
hidden Mesh hidden line removal mode
view 3-D graph viewpoint specification
rotate Rotate object about specified origin and direction
text Create Text object (Character strings)
meshgrid Generation of X and Y arrays for 3-D plots
alpha Set or query transparency properties for objects in current axes
cla Clear Axes

Operators and Special Characters


+ Plus
- Minus
* Matrix multiplication
.* Array multiplication
^ Matrix power
.^ Array power
kron Kronecker tensor product
\ Backslash or left division
/ Slash or right division
./ and .\ Array division, right and left
: Colon
() Parentheses
[] Brackets
{} Curly braces
. Decimal point
... Continuation
, Comma
; Semicolon
% Comment
! Exclamation point
' Transpose and quote
= Assignment
== Equality
<> Relational operators
& Logical and
| Logical or
~ Logical not
xor Logical exclusive or

Language Constructs and Debugging


eval Interpret strings containing MATLAB expressions

Page 68
feval Function evaluation
function Function M-files
script Script M-files
break Terminate execution of for loop or while loop
case Case switch
continue Pass control to the next iteration of for or while loop
else Conditionally execute statements
elseif Conditionally execute statements
end Terminate for, while, switch, try, and if statements or indicate last index
error Display error messages
for Repeat statements a specific number of times
if Conditionally execute statements
return Return to the invoking function
switch Switch among several cases based on expression
warning Display warning message
while Repeat statements an indefinite number of times
input Request user input
pause Halt execution temporarily
double Convert to double precision

Character String Functions


strcat String concatenation
strcmp Compare strings
char Create character array (string)
int2str Integer to string conversion
mat2str Convert a matrix into a string
num2str Number to string conversion
str2double Convert string to double-precision value
str2mat String to matrix conversion
str2num String to number conversion
bin2dec Binary to decimal number conversion
dec2bin Decimal to binary number conversion
dec2hex Decimal to hexadecimal number conversion
hex2dec Hexadecimal to decimal number conversion
hex2num Hexadecimal to double number conversion

Graphical User Interfaces


dialog Create a dialog box
errordlg Create error dialog box
helpdlg Display help dialog box
inputdlg Create input dialog box

Page 69
msgbox Create message dialog box
questdlg Create question dialog box
warndlg Create warning dialog box
guidata Store or retrieve application data
guide Open the GUI Layout Editor

Page 70

You might also like