Professional Documents
Culture Documents
Behzad.Samadi
Department of Electrical Engineering
Amirkabir University of Technology
1. Introduction
MATLAB is a technical computing environment for high-performance
numeric computation and visualization. MATLAB integrates numerical analysis,
matrix computation, signal processing, and graphics in an easy-to-use environment
where problems and solutions are expressed just as they are written mathematically -
without traditional programming.
The name MATLAB stands for matrix laboratory. In this tutorial text, we
hope to show you some of the power and flexibility offered by the MATLAB
environment. To learn better, enter the following commands into MATLAB
environment and see the results.
» A=[1 2;4 6]
A =
1 2
4 6
» A=[1 2;4 6];
» a=[1 2 3 4];
» a+2
ans =
3 4 5 6
» help i
I Imaginary unit.
The variables i and j both initially have the value sqrt(-1)
for use in forming complex quantities. For example, the
expressions 3+2i, 3+2*i, 3+2i, 3+2*j and 3+2*sqrt(-1).
all have the same value. However, both i and j may be
assigned other values, often in FOR loops and as subscripts.
See also J.
» z=(1/2)*(3+4*i)
z =
1.5000 + 2.0000i
» sqrt(-1)
ans =
0 + 1.0000i
2
» 1/0
ans =
Inf
» 0/0
ans =
NaN
» help nan
NaN Not-a-Number.
NaN is the IEEE arithmetic representation for Not-a-Number.
A NaN is obtained as a result of mathematically undefined
operations like 0.0/0.0 and inf-inf.
» log(0)
Warning: Log of zero
ans =
-Inf
» who
Your variables are:
A a ans z
» whos
Name Size Elements Bytes Density Complex
A 2 by 2 4 32 Full No
a 1 by 4 4 32 Full No
ans 1 by 1 1 8 Full No
z 1 by 1 1 16 Full Yes
» clear z ans
» who
3
named fname.mat. The data may be retrieved with LOAD.Omitting
the filename causes SAVE to use the default filename "matlab.mat".
save fname X saves only X.
save fname X Y Z saves X, Y, and Z.
» save mydata A a
» clear all
» who
Your variables are:
» load mydata
» who
» help elfun
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosh - Hyperbolic cosine.
acos - Inverse cosine.
acosh - Inverse hyperbolic cosine.
tan - Tangent.
tanh - Hyperbolic tangent.
atan - Inverse tangent.
atan2 - Four quadrant inverse tangent.
atanh - Inverse hyperbolic tangent.
sec - Secant.
sech - Hyperbolic secant.
asec - Inverse secant.
asech - Inverse hyperbolic secant.
csc - Cosecant.
csch - Hyperbolic cosecant.
acsc - Inverse cosecant.
acsch - Inverse hyperbolic cosecant.
cot - Cotangent.
coth - Hyperbolic cotangent.
acot - Inverse cotangent.
acoth - Inverse hyperbolic cotangent.
Exponential.
exp - Exponential.
log - Natural logarithm.
log10 - Common logarithm.
sqrt - Square root.
Complex.
abs - Absolute value.
angle - Phase angle.
conj - Complex conjugate.
4
imag - Complex imaginary part.
real - Complex real part.
Numeric.
fix - Round towards zero.
floor - Round towards minus infinity.
ceil - Round towards plus infinity.
round - Round towards nearest integer.
rem - Remainder after division.
sign - Signum function.
» sin(pi/2)
ans =
1
» help atan2
ATAN2 Four quadrant inverse tangent.
ATAN2(Y,X) is the four quadrant arctangent of the real parts of
the elements of X and Y. -pi <= ATAN2(Y,X) <= pi.
See also ATAN.
» atan2(-1,1)/pi
ans =
-0.2500
» atan2(1,-1)/pi
ans =
0.7500
» log(exp(1))
ans =
1
» abs(3+4i)
ans =
5
» angle(1+i)/pi
ans =
0.2500
» fix(1.2)
ans =
1
» fix(-1.2)
ans =
-1
» floor(1.2)
ans =
1
» floor(-1.2)
ans =
-2
» ceil(1.2)
5
ans =
2
» ceil(-1.2)
ans =
-1
» round(1.2)
ans =
1
» round(1.6)
ans =
2
» rem(10,3)
ans =
1
» sign(110)
ans =
1
» sign(-121)
ans =
-1
3.Matrices
» A=[1 3;5 9];B=[4 -7;10 1];
» A+B
ans =
5 -4
15 10
» A*B
ans =
34 -4
110 -26
» A'
ans =
1 5
3 9
Nonconjucated transpose
» [1+i 2*i;4-2*i 2+2*i].'
ans =
1.0000 + 1.0000i 4.0000 - 2.0000i
0 + 2.0000i 2.0000 + 2.0000i
» x=[1;2;3];y=[4;5;6];
6
Dot product
» x'*y
ans =
32
» dot(x,y)
ans =
32
Cross product
» cross(x,y)
ans =
-3
6
-3
» inv(A)
ans =
-1.5000 0.5000
0.8333 -0.1667
» ans*A
ans =
1.0000 0
0.0000 1.0000
» det(A)
ans =
-6
» trace(A)
ans =
10
» [V,D]=eig(A)
V =
-0.8863 -0.2992
0.4632 -0.9542
D =
-0.5678 0
0 10.5678
7
» [V,D]=eig(A,B)
V =
0.9759 -0.8277
0.2181 0.5612
D =
0.6858 0
0 -0.1182
» rank(A)
ans =
2
» A.*B
ans =
4 -21
50 9
» A./B
ans =
0.2500 -0.4286
0.5000 9.0000
» A.\B
ans =
4.0000 -2.3333
2.0000 0.1111
» A\B
ans =
-1.0000 11.0000
1.6667 -6.0000
If A is a square matrix, B/A is roughly the same as B*inv(A), except it is computed in
a different way.
» B/A
ans =
-11.8333 3.1667
-14.1667 4.8333
8
» b=[1;5];
» A*b
ans =
16
50
» A\b
ans =
1.0000
0.0000
» A^2
ans =
16 30
50 96
» 2.^[0 1;2 3]
ans =
1 2
4 8
» [0 1;2 3].^2
ans =
0 1
4 9
Matrix dimensions
» size(A)
ans =
2 2
» length(v)
ans =
9
8
» zeros(2)
ans =
0 0
0 0
» zeros(2,3)
ans =
0 0 0
0 0 0
» zeros(size(A))
ans =
0 0
0 0
» ones(3,2)
ans =
1 1
1 1
1 1
» eye(2)
ans =
1 0
0 1
» eye(2,3)
ans =
1 0 0
0 1 0
» rot90(A,2)
ans =
9 5
3 1
» fliplr(A)
ans =
3 1
9 5
» flipud(A)
ans =
5 9
1 3
» help reshape
RESHAPE Change size.
10
RESHAPE(X,M,N) returns the M-by-N matrix whose elements
are taken columnwise from X. An error results if X does
not have M*N elements.
» reshape(A,1,4)
ans =
1 5 3 9
» help diag
DIAG Create or extract diagonals.
If V is a row or column vector with N components,
DIAG(V,K) is a square matrix of order N+ABS(K) with the
elements of V on the K-th diagonal. K = 0 is the main
diagonal, K > 0 is above the main diagonal and K < 0 is
below the main diagonal. DIAG(V) simply puts V on the
main diagonal.
» diag(C)
ans =
1
6
11
16
» diag(ans)
ans =
1 0 0 0
0 6 0 0
0 0 11 0
0 0 0 16
» diag(C,2)
ans =
3
8
» diag(C,-1)
ans =
5
10
15
» help triu
TRIU Upper triangle.
TRIU(X) is the upper triangular part of X.
TRIU(X,K) is the elements on and above the K-th diagonal of X.
» triu(C)
11
ans =
1 2 3 4
0 6 7 8
0 0 11 12
0 0 0 16
» help tril
TRIL Lower triangle.
TRIL(X) is the lower triangular part of X.
TRIL(X,K) is the elements on and below the K-th diagonal
of X .
» tril(C,-1)
ans =
0 0 0 0
5 0 0 0
9 10 0 0
13 14 15 0
4.Polynomials
If p is a vector of length d+1 whose elements are the coefficients
of a polynomial, then y = polyval(p,x) is the value of the
polynomial evaluated at x.
y = p(1)*x^d + p(2)*x^(d-1) + ... + p(d)*x + p(d+1)
If X is a matrix or vector, the polynomial is evaluated at all
points in X.
» a=[1 6 11 6];
» polyval(a,-1)
ans =
0
» roots(a)
ans =
-3.0000
-2.0000
-1.0000
» help polyder
POLYDER Polynomial derivative.
POLYDER(P) returns the derivative of the polynomial whose
coefficients are the elements of vector P.
12
POLYDER(A,B) returns the derivative of polynomial A*B.
[Q,D] = POLYDER(B,A) returns the derivative of the
polynomial ratio B/A, represented as Q/D.
» polyder(a)
ans =
3 12 11
» [q d]=polyder(1,[1 1])
q =
-1
d =
1 2 1
» help residue
RESIDUE Partial-fraction expansion or residue computation.
[R,P,K] = RESIDUE(B,A) finds the residues, poles and direct
term of a partial fraction expansion of the ratio of two
polynomials,B(s) and A(s). If there are no multiple roots,
B(s) R(1) R(2) R(n)
---- = -------- + -------- + ... + -------- + K(s)
A(s) s - P(1) s - P(2) s - P(n)
Vectors B and A specify the coefficients of the polynomials in
descending powers of s. The residues are returned in the
column vector R, the pole locations in column vector P, and the
direct terms in row vector K. The number of poles is
n = length(A)-1 = length(R) = length(P)
The direct term coefficient vector is empty if length(B)<length(A)
;otherwise
length(K) = length(B)-length(A)+1
If P(j) = ... = P(j+m-1) is a pole of multplicity m, then the
expansion includes terms of the form
R(j) R(j+1) R(j+m-1)
-------- + ------------ + ... + ------------
s - P(j) (s - P(j))^2 (s - P(j))^m
[B,A] = RESIDUE(R,P,K), with 3 input arguments and 2 output
arguments,converts the partial fraction expansion back to the
polynomials with coefficients in B and A.
Warning:
Numerically, the partial fraction expansion of a ratio of
polynomials represents an ill-posed problem. If the
denominator polynomial, A(s),is near a polynomial with multiple
roots, then small changes in the data, including roundoff
errors, can make arbitrarily large changes in the resulting
poles and residues. Problem formulations making use of state-
space or zero-pole representations are preferable.
1 0.5 1 0.5
Example: = − +
x(x + 1)(x + 2) x x +1 x + 2
» [r p k]=residue(1,[1 3 2 0])
r =
0.5000
13
-1.0000
0.5000
p =
-2
-1
0
k =
[]
» [b a]=residue(r,p,k)
b =
0 0 1
a =
1 3 2 0
» polyvalm(a,X)
ans =
0 -16
-24 -24
» polyval(a,X)
ans =
0 0
0 -6
5.Data analysis
rand(n) is an n-by-n matrix with random entries, ordinarily
chosen from a uniform distribution on the interval (0.0,1.0).
rand(m,n) or rand([m,n]) is an m-by-n matrix with random entries.
rand(size(A)) is the same size as A.
rand with no arguments is a scalar whose value changes each time
it is referenced.
» u=rand(1,4)
u =
0.2190 0.0470 0.6789 0.6793
» help max
MAX Largest component.
For vectors, MAX(X) is the largest element in X. For
matrices, MAX(X) is a vector containing the maximum element
from each column. [Y,I] = MAX(X) stores the indices of the
maximum values in vector I. MAX(X,Y) returns a matrix the
same size as X and Y with the largest elements taken from X
or Y. When complex, the magnitude MAX(ABS(X)) is used.
14
See also MIN, MEDIAN, MEAN, SORT.
» [mx i]=max(u)
mx =
0.6793
i =
4
» [mn j]=min(u)
mn =
0.0470
j =
2
» mean(u)
ans =
0.4060
Median value.
» median(u)
ans =
0.4489
Standard deviation.
» std(u)
ans =
0.3230
Sum of the elements.
» sum(n)
ans =
2.2185
» prod(n)
ans =
0.0193
randn is similar to rand except that it produces normally distributed random numbers
and matrices.
randn and rand have separate generators, each with its own seed.
» n=randn(1,4)
n =
1.1650 0.6268 0.0751 0.3516
15
» max(u,n)
ans =
1.1650 0.6268 0.6789 0.6793
» max(A)
ans =
7 8 9
» cumsum(A)
ans =
1 2 3
5 7 9
12 15 18
» cumprod(A)
ans =
1 2 3
4 10 18
28 80 162
6.Graphics
» v=rand(1,100);
» help hist
HIST Plot histograms.
HIST(Y) plots a histogram with 10 equally spaced bins between
the minimum and maximum values in Y, showing the distribution
of the elements in vector Y.
HIST(Y,N), where N is a scalar, uses N bins.
HIST(Y,X), where X is a vector, draws a histogram using the
bins specified in X.
[N,X] = HIST(...) does not draw a graph, but returns vectors
X and N such that BAR(X,N) is the histogram.
» hist(v)
16
14
12
10
0
0 0.2 0.4 0.6 0.8 1
» help bar
BAR Bar graph.
BAR(Y) draws a bar graph of the elements of vector Y.
BAR(X,Y) draws a bar graph of the elements of vector Y at
the locations specified in vector X. The X-values must
be in ascending order. If the X-values are not evenly spaced,
the interval chosen is not symmetric about each data point.
Instead,the bars are drawn midway between adjacent X-values.
The endpoints simply adopt the internal intervals for the
external ones needed.
If X and Y are matrices the same size, one bar graph per column
is drawn.
[XX,YY] = BAR(X,Y) does not draw a graph, but returns vectors
X and Y such that PLOT(XX,YY) is the bar chart.
17
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
-3 -2 -1 0 1 2 3
» help stairs
STAIRS Stairstep graph (bar graph without internal lines).
Stairstep plots are useful for drawing time history plots of
digital sampled-data systems.
STAIRS(Y) draws a stairstep graph of the elements of vector Y.
STAIRS(X,Y) draws a stairstep graph of the elements in vector Y
at the locations specified in X. The X-values must be in
ascending order and evenly spaced.
[XX,YY] = STAIRS(X,Y) does not draw a graph, but returns
vectors X and Y such that PLOT(XX,YY) is the stairstep graph.
See also BAR, HIST.
» stairs(x,exp(-x.*x))
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
-3 -2 -1 0 1 2 3
fill(x,y,c) fills the 2-D polygon defined by vectors x and y with the color specified by c.
The vertices of the polygon are specified by pairs of components of x and y.If necessary,
the polygon is closed by connecting the last vertex to the first.
18
If c is a single character string chosen from the list 'r','g','b','c','m','y','w','k', or an RGB
row vector triple, [r g b], the polygon is filled with the constant specified color.
» t=(1/16:1/8:1)'*2*pi;
» fill(sin(t),cos(t),'k')
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-1 -0.5 0 0.5 1
» help plot
PLOT Plot vectors or matrices.
PLOT(X,Y) plots vector X versus vector Y. If X or Y is a
matrix,then the vector is plotted versus the rows or columns of
the matrix,whichever line up.
PLOT(Y) plots the columns of Y versus their index.
If Y is complex,PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is ignored.
y yellow . point
m magenta o circle
c cyan x x-mark
r red + plus
g green - solid
b blue * star
w white : dotted
k black -. dashdot
-- dashed
19
The PLOT command, if no color is specified, makes automatic use
of the colors specified by the axes ColorOrder property. The
default ColorOrder is listed in the table above for color
systems where the default is yellow for one line, and for
multiple lines, to cycle through the first six colors in the
table. For monochrome systems,PLOT cycles over the axes
LineStyleOrder property.
» x=linspace(0,10,50);
» plot(x,bessel(0,x),'-',x,bessel(1,x),'--')
0.5
-0.5
0 2 4 6 8 10
Graph annotation:
» xlabel('x');ylabel('f(x)');title('Bessel functions')
» text(1,.85,'J0');text(4,.1,'J1')
20
Bessel functions
1
J0
0.5
f(x)
J1
0
-0.5
0 2 4 6 8 10
x
» help semilogx
SEMILOGX Semi-log scale plot.
SEMILOGX(...) is the same as PLOT(...), except a
logarithmic (base 10) scale is used for the X-axis.
-20
-40
Degree
-60
-80
-100
-2 -1 0 1 2
10 10 10 10 10
semilogy(...) is the same as plot(...), except a logarithmic (base 10) scale is used for
the Y-axis.
21
loglog(...) is the same as plot(...), except logarithmic scales are used for both the
X- and Y- axes.
» help polar
POLAR Polar coordinate plot.
POLAR(THETA, RHO) makes a plot using polar coordinates of
the angle THETA, in radians, versus the radius RHO.
POLAR(THETA,RHO,S) uses the linestyle specified in string S.
See PLOT for a description of legal linestyles.
» theta=0:2*pi/100:2*pi;
» r=theta/(2*pi);
» polar(theta,r);title('Polar Plot')
Polar Plot
901
120 60
0.8
0.6
150 30
0.4
0.2
180 0
210 330
240 300
270
» x=linspace(0,7,50);
» plot(x,sin(x))
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
22
» plot(x,cos(x))
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
hold off returns to the default mode whereby plot commands erase the previous plots.
hold, by itself, toggles the hold state.
» hold off
Grid lines.
» grid
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
» help axis
AXIS Plot axis scaling and appearance.
23
AXIS([XMIN XMAX YMIN YMAX]) sets scaling for the x- and y-axes
on the current plot.
AXIS([XMIN XMAX YMIN YMAX ZMIN ZMAX]) sets the scaling for the
x-, y- and z-axes on the current 3-D plot.
AXIS('image') sets the aspect ratio and the axis limits so the
image in the current axes has square pixels.
S1 = 'auto' or 'manual'.
S2 = 'on' or 'off'.
S3 = 'xy' or 'ij'.
» axis([0 7 -2 2])
24
2
1.5
0.5
-0.5
-1
-1.5
-2
0 1 2 3 4 5 6 7
» help subplot
SUBPLOT Create axes in tiled positions.
SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into
an m-by-n matrix of small axes, selects the p-th axes for
for the current plot, and returns the axis handle. The axes
are counted along the top row of the Figure window, then the
second row, etc. For example,
SUBPLOT(2,1,1), PLOT(income)
SUBPLOT(2,1,2), PLOT(outgo)
plots income on the top half of the window and outgo on the
bottom half.
SUBPLOT(m,n,p), if the axis already exists, makes it current.
SUBPLOT(H), where H is an axis handle, is another way of making
an axis current for subsequent plotting commands.
If a SUBPLOT specification causes a new axis to overlap an
existing axis, the existing axis is deleted. For example,
the statement SUBPLOT(1,1,1) deletes all existing smaller
axes in the Figure window and creates a new full-figure axis.
» subplot(211);plot(x,sin(x));grid;subplot(212);plot(x,cos(x));grid
0.5
0
-0.5
-1
0 1 2 3 4 5 6 7
1
0.5
0
-0.5
-1
0 1 2 3 4 5 6 7
25
» help ginput
GINPUT Graphical input from a mouse or cursor.
[X,Y] = GINPUT(N) gets N points from the current axes and
returns the X- and Y-coordinates in length N vectors X and Y.
The cursor can be positioned using a mouse (or by using the
Arrow Keys on some systems). Data points are entered by
pressing a mouse button or any key on the keyboard. A carriage
return terminates the input before N points are entered.
» help zoom
ZOOM Zoom in and out on a 2-D plot.
ZOOM ON turns zoom on for the current figure. Click
the left mouse button to zoom in on the point under the
mouse. Click the right mouse button to zoom out
(shift-click on the Macintosh). Each time you click,
the axes limits will be changed by a factor of 2 (in or out).
You can also click and drag to zoom into an area.
3D Graphics
» t=0:pi/50:10*pi;
» plot3(sin(t),cos(t),t,'k')
40
30
20
10
0
1
0.5 1
0 0.5
0
-0.5 -0.5
-1 -1
26
» fill3(rand(3,1),rand(3,1),rand(3,1),'k')
0.5
0.4
0.3
1
0.8 0.6
0.5
0.6 0.4
0.4 0.3
[X,Y] = meshgrid(x,y) transforms the domain specified by vectors x and y into arrays X
and Y that can be used for the evaluation of functions of two variables and 3-D surface
plots.The rows of the output array X are copies of the vector x and the columns of the
output array Y are copies of the vector y.
» [X,Y]=meshgrid(-2:.2:2,-2:.2:2);
» help contour
CONTOUR Contour plot.
CONTOUR(Z) is a contour plot of matrix Z treating the values in
Z as heights above a plane.
» Z=X.*exp(-X.^2-Y.^2);
» contour(X,Y,Z,10)
27
2
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
» help mesh
MESH 3-D mesh surface.
MESH(X,Y,Z,C) plots the colored parametric mesh defined by
four matrix arguments. The view point is specified by VIEW.
The axis labels are determined by the range of X, Y and Z,
or by the current setting of AXIS. The color scaling is
determined by the range of C, or by the current setting of
CAXIS.The scaled color values are used as indices into the
current COLORMAP.
AXIS, CAXIS, COLORMAP, HOLD, SHADING and VIEW set figure, axes,
and surface properties which affect the display of the mesh.
» mesh(X,Y,Z)
28
0.5
-0.5
2
1 2
0 1
0
-1 -1
-2 -2
» help contour3
CONTOUR3 3-D contour plot.
CONTOUR3(Z) plots the contour lines of Z in 3-D.
CONTOUR3(Z,N) plots N contour lines in 3-D. The default is
N=10.CONTOUR3(X,Y,Z) or CONTOUR3(X,Y,Z,N) uses the matrices X
and Y to define the axis limits.
» contour3(X,Y,Z)
0.4
0.2
-0.2
-0.4
2
1 2
0 1
0
-1 -1
-2 -2
» help meshc
MESHC Combination MESH/CONTOUR plot.
MESHC(...) is the same as MESH(...) except that a contour plot
29
is drawn beneath the mesh.
» meshc(X,Y,Z)
0.5
-0.5
2
1 2
0 1
0
-1 -1
-2 -2
» help meshz
MESHZ 3-D mesh with reference plane.
MESHZ(...) is the same as MESH(...) except that a "curtain" or
reference plane is drawn beneath.
This routine only works for surfaces defined on a rectangular
grid. The matrices X and Y define the axis limits only.
See also MESH.
» meshz(X,Y,Z)
0.5
-0.5
2
1 2
0 1
0
-1 -1
-2 -2
Graph annotation:
» xlabel('X');ylabel('Y');zlabel('Z');title('Z=X*exp(-(X^2+Y^2))')
30
Z=X*exp(-(X^2+Y^2))
0.5
0
Z
-0.5
2
1 2
0 1
0
-1 -1
Y -2 -2 X
» help view
VIEW 3-D graph viewpoint specification.
VIEW(AZ,EL) and VIEW([AZ,EL]) set the angle of the view from
which an observer sees the current 3-D plot. AZ is the azimuth
or horizontal rotation and EL is the vertical elevation (both
in degrees). Azimuth revolves about the z-axis, with positive
values indicating counter-clockwise rotation of the viewpoint.
Positive values of elevation correspond to moving above the
object; negative values move below.
VIEW([X Y Z]) sets the view angle in cartesian coordinates. The
magnitude of vector X,Y,Z is ignored.
» view([1 1 1])
31
Z=X*exp(-(X^2+Y^2))
0.5
0
Z
-0.5
-2 -2
-1 -1
0 0
1 1
2 2 X
Y
» surf(X,Y,Z)
0.5
-0.5
2
1 2
0 1
0
-1 -1
-2 -2
» surfc(X,Y,Z)
32
0.5
-0.5
2
1 2
0 1
0
-1 -1
-2 -2
» help surfl
waterfall(...) is the same as mesh(...) except that the column lines of the mesh are not
drawn.
33
» waterfall(X,Y,Z)
0.5
-0.5
30
20 30
20
10 10
0 0
-1
-2
2
1 2
0 1
0
-1 -1
-2 -2
34
flag - Alternating red, white, blue, and black color map.
7.Numerical Techniques
Numerical Differentiation:
diff(x), for a vector x, is [x(2)-x(1) x(3)-x(2) ... x(n)-x(n-1)].
diff(X), for a matrix X, is the matrix of column differences,[X(2:n,:) - X(1:n-1,:)].
diff(X,n) is the n-th difference function.
» h = .1; x = 0:h:pi;
» plot(x,2*cos(x.^2).*x,'k-',x(2:length(x)),diff(sin(x.^2))/h,'k--')
-2
-4
-6
-8
0 0.5 1 1.5 2 2.5 3 3.5
Numerical Integration:
25
We know that ∫ x dx = 78 .Let's compute this integral using several numerical
4
methods.
» x=4:0.1:25;y=sqrt(x);
» trapz(x,y)
ans =
77.9999
35
q = quad('f ',a,b) approximates the integral of f(x) from a to b to within a relative
error of 1e-3. 'f ' is a string containing the name of the function. Function f must
return a
vector of output values if given a vector of input values.q = quad('f ',a,b,tol) integrates
to a relative error of tol.quad uses an adaptive recursive Simpson's rule.
» quad('sqrt',4,25)
ans =
77.9997
q=quad8('f ',a,b) is the same as q = quad('f ',a,b) except that it uses an adaptive
recursive Newton Cotes 8 panel rule.
» quad8('sqrt',4,25)
ans =
78.0000
» help ode23
ODE23 Solve differential equations, low order method.
ODE23 integrates a system of ordinary differential equations
using 2nd and 3rd order Runge-Kutta formulas.
[T,Y] = ODE23('yprime', T0, Tfinal, Y0) integrates the system
of ordinary differential equations described by the M-file
YPRIME.M,over the interval T0 to Tfinal, with initial
conditions Y0.
[T, Y] = ODE23(F, T0, Tfinal, Y0, TOL, 1) uses tolerance TOL
and displays status while the integration proceeds.
INPUT:
F - String containing name of user-supplied problem
description.
Call: yprime = fun(t,y) where F = 'fun'.
t - Time (scalar).
y - Solution column-vector.
yprime - Returned derivative column-vector;
yprime(i) = dy(i)/dt.
t0 - Initial value of t.
tfinal- Final value of t.
y0 - Initial value column-vector.
tol - The desired accuracy. (Default: tol = 1.e-3).
trace - If nonzero, each step is printed. (Default: trace = 0).
OUTPUT:
T - Returned integration time points (column-vector).
Y - Returned solution, one solution column-vector per tout-
value.
36
Let's solve the following ODE:
y ′ = 2tcos 2 (y)
The M-file that defines the function used to compute values of derivative is the
following:
function dy=fun(t,y)
% This function evaluates a first-order ODE
dy=2*t.*cos(y).^2
To solve the above ODE over interval [0,2],assuming that the initial condition y(0) is π /4,
we use these MATLAB statements:
» [t y]=ode23('fun',0,2,pi/4);
» plot(t,y,'k')
1.4
1.3
1.2
1.1
0.9
0.8
0.7
0 0.5 1 1.5 2
NOTE: ode45 is the same as ode23 except that it uses 4th and 5th order Runge-Kutta
formulas.
» fmin('cos',3,4)
ans =
3.1416
» fzero('sin',3)
ans =
3.1416
37
8.Programming Language
» help script
SCRIPT Scripts M-files.
A SCRIPT file is an external file that contains a sequence
of MATLAB statements. By typing the filename, subsequent
MATLAB input is obtained from the file. SCRIPT files have
a filename extension of ".m" and are often called "M-files".
To make a SCRIPT file into a function, see FUNCTION.
» help function
Logical characteristics:
exist('A') returns:
0 if A does not exist
1 if A is a variable in the workspace
2 if A is an M-file on MATLAB's search path
3 if A is a MEX-file on MATLAB's search path
4 if A is a compiled SIMULINK function
5 if A is a built-in MATLAB function
» exist('y')
ans =
1
For vectors, any(V) returns 1 if any of the elements of the vector are non-zero.
Otherwise it returns 0. For matrices,any(X) operates on the columns of X,
returning a row vector of 1's and 0's.
» any([0 1 0 0])
ans =
1
38
For vectors, all(V) returns 1 if all of the elements of the vector are non-zero.
Otherwise it returns 0. For matrices,all(X) operates on the columns of X,
returning a row vector of 1's and 0's.
» all([1 0 1 1])
ans =
0
[I,J] = find(X) returns the row and column indices of the nonzero entries in the matrix
X.This is often used with sparse matrices.
[I,J,V] = find(X) also returns a column vector of the nonzero entries in X. Note that
find(X) and find(X~=0) will produce the same I and J, but the latter will
produce a V with all 1's.
» i=find((1:10)>5)
i =
6 7 8 9 10
isnan(X) returns 1's where the elements of X are NaN's and 0's where they are not.
» isnan([pi NaN Inf -Inf])
ans =
0 1 0 0
isinf(X) returns 1's where the elements of X are +Inf or -Inf and 0's where they are not.
» isinf([pi NaN Inf -Inf])
ans =
0 0 1 1
finite(X) returns 1's where the elements of X are finite and 0's where they are not.
» finite([pi NaN Inf -Inf])
ans =
1 0 0 0
39
Control Flow:
» help if
IF Conditionally execute statements.
The general form of an IF statement is:
IF variable, statements, END
The statements are executed if the real part of the variable
has all non-zero elements. The variable is usually the result
of expr rop expr where rop is ==, <, >, <=, >=, or ~=.
For example:
IF I == J
A(I,J) = 2;
ELSEIF ABS(I-J) == 1
A(I,J) = -1;
ELSE
A(I,J) = 0;
END
» help for
FOR Repeat statements a specific number of times.
The general form of a FOR statement is:
FOR I = 1:N,
FOR J = 1:N,
A(I,J) = 1/(I+J-1);
END
END
» help while
WHILE Repeat statements an indefinite number of times.
The general form of a WHILE statement is:
E = 0*A; F = E + EYE(E); N = 1;
WHILE NORM(E+F-E,1) > 0,
E = E + F;
F = A*F/N;
N = N + 1;
END
» help break
BREAK Terminate the execution of a loop.
BREAK terminates the execution of loops.
40
In nested loops, BREAK exits from the
innermost loop only.
» help return
RETURN Return to invoking function.
RETURN causes a return to the invoking function or to the
keyboard.
» help error
ERROR Display message and abort function.
ERROR('MSG') displays the text MSG and causes an error exit
from an M-file to the keyboard. If the string is an empty
matrix, no action is taken.
Interactive Input:
» help input
INPUT Prompt for user input.
INPUT('How many apples') gives the user the prompt in the
text string and then waits for input from the keyboard.
The input can be any MATLAB expression, which is evaluated,
using the variables in the current workspace, and the result
returned as the value of the function.
» help keyboard
KEYBOARD Invoke the keyboard as if it were a Script-file.
KEYBOARD invokes the keyboard as if it were a Script-file.
When placed in an M-file, KEYBOARD stops execution of the
file and gives control to the user's keyboard. The special
status is indicated by a double prompt. Variables may be
examined or changed - all MATLAB commands are valid. The
keyboard mode is terminated by executing the command RETURN
(i.e. typing the six letters R-E-T-U-R-N and pressing the
return key). Control returns to the invoking M-file.
» help menu
MENU Generate a menu of choices for user input.
K = MENU('Choose a color','Red','Blue','Green') displays on
the screen:
1) Red
2) Blue
3) Green
41
PAUSE OFF indicates that any subsequent PAUSE or PAUSE(n)
commands should not actually pause. This allows normally
interactive scripts to run unattended.
PAUSE ON indicates that subsequent PAUSE commands should pause.
for n = 1:12
eval(['M' num2str(n) ' = magic(n)'])
end
D = ['odedemo '
'quaddemo'
'fitdemo '];
n = input('Select a demo number: ');
eval(D(n,:))
» help feval
FEVAL Function evaluation.
If F is a string containing the name of a function (usually
defined by an M-file), then FEVAL(F,x1,...,xn) evaluates
that function at the given arguments. For example,
F = 'foo', FEVAL(F,9.64) is the same as foo(9.64).
FEVAL is usually used inside functions which have the names
of other functions as arguments.
» help global
GLOBAL Define global variables.
GLOBAL X Y Z defines X, Y, and Z as global in scope.
Ordinarily, each MATLAB function, defined by an M-file, has its
own local variables, which are separate from those of other
functions,and from those of the base workspace and non-function
scripts.
However, if several functions, and possibly the base workspace,
all declare a particular name as GLOBAL, then they all share
a single copy of that variable. Any assignment to that
variable,in any function, is available to all the other
functions declaring it GLOBAL.
42
Stylistically, global variables often have long names with all
capital letters, but this is not required.
» help nargchk
NARGCHK Check number of input arguments.
Return error message if not between low and high.
If it is, return empty matrix.
String comparison.
43
strcmp(S1,S2) returns 1 if strings S1 and S2 are the same otherwise 0.
» strcmp('MATLAB','matlab')
ans =
0
k = findstr(S1,S2) returns the starting indices of any occurrences of the shorter of the
two strings in the longer.
» findstr('matlab','ab')
ans =
5
» help strtok
STRTOK First token in the supplied string.
STRTOK(S,D) returns the first token delimited by the specified
delimiters D in the supplied string S. It also optionally
returns the remainder of the original string. D is an array
of character delimiters. If no delimiters are supplied,
"white space" is assumed.
» strtok('MATLAB: A Tutorial',':')
ans =
MATLAB
String to number conversion.
num2str - Convert number to string.
» num2str(12.5)
ans =
12.5
44
» int2str(12.5)
ans =
12
10.Miscellaneous
Time and dates:
clock returns a six element row vector containing the current time and date in decimal
form:
clock = [year month day hour minute seconds]
The first five elements are integers. The seconds element is accurate to several digits
beyond the decimal point.
cputime returns the CPU time in seconds that has been used by the MATLAB
process since MATLAB started.
For example:
t=cputime; your_operation; cputime-t
returns the cpu time used to run your_operation.
The return value may overflow the internal representation and wrap around.
etime(T1,T0) returns the time in seconds that has elapsed between vectors T1 and T0.
The two vectors must be six elements long, in the format returned by clock:
T = [Year Month Day Hour Minute Second]
45
what - Directory listing of M-, MAT- and MEX-files.
type - List M-file.
» type fun
function dy=fun(t,y)
dy=2*t.*cos(y).^2;
DOS: path(P,'TOOLS\GOODSTUFF')
See also GETENV, WHAT, CD, DIR.
diary file_name causes a copy of all subsequent terminal input and most of the
resulting output to be written on the named file. diary off suspends it. diary on
turns it back on.
diary, by itself, toggles the diary state.
Controlling the command window:
clc - Clear command window.
home - Send cursor home.
echo - Echo commands inside script files.
more - Control paged output in command window.
format -set output format
All computations in MATLAB are done in double precision.
format may be used to switch between different output
display formats as follows:
format Default. Same as SHORT.
format short Scaled fixed point format with 5 digits.
format long Scaled fixed point format with 15 digits.
format short e Floating point format with 5 digits.
46
format long e Floating point format with 15 digits.
format hex Hexadecimal format.
format + The symbols +, - and blank are printed for positive, negative
and zero elements.Imaginary parts are ignored.
format bank Fixed format for dollars and cents.
format comapct Suppress extra line-feeds.
format loose Puts the extra line-feeds back in.
format rat Approximation by ratio of small integers.
» help flops
FLOPS Count of floating point operations.
FLOPS returns the cumulative number of floating point
operations. FLOPS(0) resets the count to zero.
It is not feasible to count absolutely all floating point
operations, but most of the important ones are counted.
Additions and subtractions are one flop if real and two if
complex. Multiplications and divisions count one flop each
if the result is real and six flops if it is not.
Elementary functions count one if real and more if complex.
Some examples. If A and B are real N-by-N matrices, then
A + B counts N^2 flops,
A * B counts 2*N^3 flops,
A ^ 100 counts 99*2*N^3 flops,
LU(A) counts roughly (2/3)*N^3 flops.
References
®
[1] D.M.Etter,Engineering Problem Solving with MATLAB ,Prentice Hall,1997
®
[2] MATLAB Reference Guide,The MathWorks,Inc,1992
47