Matlab Tutorial
Matlab Tutorial
Matlab Tutorial
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.
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.
• 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:
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:
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
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
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
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.
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.
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.
Address is counted from left corner, from top to bottom or from left to right.
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
2.4 String
You define string by
>>a='test'
a=
test
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
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
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
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.
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.
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.
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)
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')
>> x = -10:0.2:10;
>> y = x.*sin(x);
>> plot(x,y,'x')
>> 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.
>> 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.
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:
>> 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')
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.
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.
Page 27
\mu µ \Upsilon \circ º
\nu \Phi \pm ±
\xi \Psi \geq
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])
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)
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:
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
[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
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,'*')
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')
>> 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
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)
>> [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)
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,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
You can create colormaps with MATLAB’s array operations or you can use any of several
functions that generate useful maps, including:
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).
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:
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,
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);
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:
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.
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:
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.
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
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
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 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.
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')
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.
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.
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:
Page 58
9.2 Programming GUIs
Example 1:
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.
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.
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
Page 64
Elementary Math Functions
abs Absolute value and complex magnitude
acos, acosh Inverse cosine and inverse hyperbolic cosine in radians
Page 65
tand Tangent of argument in degree
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
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
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