You are on page 1of 47

MATLAB®: A TUTORIAL

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.

2.Expressions and Variables

» 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

Warning: Divide by zero

ans =
Inf

» 0/0

Warning: Divide by zero

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.

See also 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

Grand total is 10 elements using 88 bytes

clear clear various quantities from the workspace.


clear removes all variables from the workspace.
clear variables does the same thing.
clear X removes variable or function X from the workspace.

» clear z ans
» who

Your variables are:


A a
save save workspace variables on disk.
save fname saves all workspace variables to the binary "MAT-file"

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

Your variables are:


A a

» help elfun

Elementary math functions.

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

» [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

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

eig(A) is a vector containing the eigenvalues of a square matrix A.


» eig(A)
ans =
-0.5678
10.5678

[V,D] = eig(A) produces a diagonal matrix D of


eigenvalues and a full matrix V whose columns are the
corresponding eigenvectors so that A*V = V*D.

» [V,D]=eig(A)
V =
-0.8863 -0.2992
0.4632 -0.9542
D =
-0.5678 0
0 10.5678

[V,D] = eig(A,B) produces a diagonal matrix D of general-


ized eigenvalues and a full matrix V whose columns are the
corresponding eigenvectors so that A*V = B*V*D.

7
» [V,D]=eig(A,B)
V =
0.9759 -0.8277
0.2181 0.5612
D =
0.6858 0
0 -0.1182

If A is an N by N matrix, poly(A) is a row vector with


N+1 elements which are the coefficients of the
characteristic polynomial, det(lambda*eye(size(A)) - A) .
» poly(A)
ans =
1.0000 -10.0000 -6.0000

rank is the number of linearly independent rows or columns.

» rank(A)
ans =
2

A.*B is the element-by-element product of the arrays A and B .

» A.*B
ans =
4 -21
50 9

A./B is the matrix with elements A(i,j)/B(i,j)

» A./B
ans =
0.2500 -0.4286
0.5000 9.0000

A.\B is the matrix with elements B(i,j)/A(i,j)

» A.\B
ans =
4.0000 -2.3333
2.0000 0.1111

If A is a square matrix, A\B is roughly the same as inv(A)*B, except it is computed in


a different way.

» 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

x=A\b is the solution of Ax=b

» A\b
ans =
1.0000
0.0000

A^p is A to the power p.

» A^2
ans =
16 30
50 96

A.^B is the matrix with elements A(i,j) to the B(i,j) power.

» [2 2;2 2].^[0 1;2 3]


ans =
1 2
4 8

» 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

» A=[1 2 3;4 5 6];


» size(A,1)
» ans =
2
» size(A,2)
ans =
3

» v=[1.02 2.1 3.5 4 5.2 16 1.7 .8];

» 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,k) is the k*90 degree rotation of A, k = +-1,+-2,...

» rot90(A,2)
ans =
9 5
3 1

fliplr flip matrix in the left/right direction.

» fliplr(A)
ans =
3 1
9 5

flipud flip matrix in the up/down direction.

» 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.

If X is a matrix, DIAG(X,K) is a column vector formed from


the elements of the K-th diagonal of X. DIAG(X) is the main
diagonal of X. DIAG(DIAG(X)) is a diagonal matrix.

» C=[1 2 3 4;5 6 7 8;9 10 11 12;13 14 15 16]


C =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

» 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

conv is polynomial multipication.


» b=[1 2 3];
» conv(a,b)
ans =
1 8 26 46 45 18

[q r]=deconv(a,b) is polynomial division.


The result of dividing a by b is quotient q and reminder r.
» [q r]=deconv(a,b)
q =
1 4
r =
0 0 0 -6
roots(a) computes the roots of the polynomial whose coefficients

» 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

» polyder([1 2],[1 3])


ans =
2 5

» [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

If p is a vector whose elements are the coefficients of a


polynomial, then polyvalm(p,X) is the value of the
polynomial evaluated with matrix argument X.

» X=[-1 -2;-3 -4]


X =
-1 -2
-3 -4

» 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

Average or mean value.

» 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

Product of the elements.

» 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

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


A =
1 2 3
4 5 6
7 8 9

» max(A)
ans =
7 8 9

Cumulative sum of the elements.

» cumsum(A)
ans =
1 2 3
5 7 9
12 15 18

Cumulative product of the elements.

» 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.

See also BAR.

» 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.

See also STAIRS, HIST.


BAR(X,'linetype') or BAR(X,Y,'linetype') uses the plot linetype
specified. See PLOT for details.

Define x=[-2.9 -2.7 -2.5 ... 2.7 2.9]


» x=-2.9:0.2:2.9;
» bar(x,exp(-x.*x))

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.

Various line types, plot symbols and colors may be obtained


with PLOT(X,Y,S) where S is a 1, 2 or 3 character string made
from the following characters:

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

For example, PLOT(X,Y,'c+') plots a cyan plus at each data


point.

PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined


by the (X,Y,S) triples, where the X's and Y's are vectors or
matrices and the S's are strings.
For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with
a solid yellow line interpolating green circles at the data
points.

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.

PLOT returns a column vector of handles to LINE objects, one


handle per line.

The X,Y pairs, or X,Y,S triples, can be followed by


parameter/value pairs to specify additional properties
of the lines.

See also SEMILOGX, SEMILOGY, LOGLOG, GRID, CLF, CLC, TITLE,


XLABEL, YLABEL, AXIS, AXES, HOLD, and SUBPLOT.

x is a vector of 50 points linearly equaly spaced between 0 and 10.

» x=linspace(0,10,50);

Plot Bessel functions of order 0 and 1 ( J 0 (x) ,J 1 (x) ).

» 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

NOTE: gtext place text on a 2-D graph using a mouse.

» 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.

See also PLOT.

x is a vector of 50 points logarithmically equaly spaced between decades 10 −2 and 10 2 .


» x=logspace(-2,2,50);
1
Plot the phase angle of versus ω .
1 + jω
» semilogx(x,angle(1./(1+i*x))*180/pi);
» ylabel('Degree')

-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.

See also PLOT, LOGLOG, SEMILOGX, SEMILOGY.

» 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

hold on holds the current graph.


» hold on

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

ishold returns 1 if hold is on, and 0 if it is off.


» ishold
ans =
0

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('auto') returns the axis scaling to its default, automatic


mode where, for each plot, xmin = min(x), xmax = max(x), etc.

V = AXIS returns a row vector containing the scaling for the


current plot. If the current plot is two-dimensional, V has
four components; if it is three-dimensional, V has six
components.

AXIS(AXIS) freezes the scaling at the current limits, so that


if HOLD is turned on, subsquent plots will use the same limits.

AXIS('ij') puts MATLAB into its "matrix" axes mode. The


coordinate system origin is at the upper left corner. The i
axis is vertical and is numbered from top to bottom. The j
axis is horizontal and is numbered from left to right.

AXIS('xy') puts MATLAB into its default "Cartesian" axes mode.


The coordinate system origin is at the lower left corner. The
x axis is horizontal and is numbered from left to right. The y
axis is vertical and is numbered from bottom to top.

AXIS('equal') changes the current axis box size so that equal


tick mark increments on the x- and y-axis are equal in size.
This makes PLOT(SIN(X),COS(X)) look like a circle, instead of
an oval.

AXIS('square') makes the current axis box square in size.


AXIS('image'), for images, makes the aspect ratio the same size
as the image.

AXIS('normal') restores the current axis box to full size and


removes any restrictions on the scaling of the units.
This undoes the effects of AXIS('square') and AXIS('equal').

AXIS('image') sets the aspect ratio and the axis limits so the
image in the current axes has square pixels.

AXIS('off') turns off all axis labeling and tick marks.


AXIS('on') turns axis labeling and tick marks back on.

[S1,S2,S3] = AXIS('state') returns strings indicating the


current setting of three axis properties.

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

NOTE: clf clears current figure.

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.

[X,Y] = GINPUT gathers an unlimited number of points until the


return key is pressed.

[X,Y,BUTTON] = GINPUT(N) returns a third result, BUTTON, that


contains a vector of integers specifying which mouse button was
used (1,2,3 from left) or ASCII numbers if a key on the
keyboard was used.

» 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.

ZOOM OFF turns zoom off. ZOOM with no arguments


toggles the zoom status. ZOOM OUT returns the plot
to its initial (full) zoom.

3D Graphics

plot3(...) is a three-dimensional analogue of plot(...).

» 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

fill3(...) is a three-dimensional analogue of fill(...).

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.

CONTOUR(X,Y,Z), where X and Y are vectors, specifies the X- and


Y-axes used on the plot.

CONTOUR(Z,N) and CONTOUR(X,Y,Z,N) draw N contour lines,


overriding the default automatic value.
CONTOUR(Z,V) and CONTOUR(X,Y,Z,V) draw LENGTH(V) contour lines
at the values specified in vector V.

CONTOUR(...,'linetype') draws with the color and linetype


specified,as in the PLOT command.
C = CONTOUR(...) returns contour matrix C as described in
CONTOURC and used by CLABEL.

[C,H] = CONTOUR(...) returns a column vector H of handles to


LINE objects, one handle per line.
See also CLABEL, CONTOURC, CONTOUR3, GRADIENT, QUIVER, PRISM.

» 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.

MESH(X,Y,Z) uses C = Z, so color is proportional to mesh


height.

MESH(x,y,Z) and MESH(x,y,Z,C), with two vector arguments


replacing the first two matrix arguments, must have length(x)=n
and length(y) = m where [m,n] = size(Z). In this case, the
vertices of the mesh lines are the triples (x(j), y(i),Z(i,j)).
Note that x corresponds to the columns of Z and y corresponds
to the rows.

MESH(Z) and MESH(Z,C) use x = 1:n and y = 1:m. In this case,


the height, Z, is a single-valued function, defined over a
geometrically rectangular grid.

MESH returns a handle to a SURFACE object.

AXIS, CAXIS, COLORMAP, HOLD, SHADING and VIEW set figure, axes,
and surface properties which affect the display of the mesh.

See also SURF, MESHC, MESHZ, WATERFALL.

» 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.

C = CONTOUR3(...) returns contour matrix C as described in


CONTOURC.
[C,H] = CONTOUR3(...) returns a column vector H of handles to
LINE objects, one handle per line.

See also CONTOURC, CONTOUR.

» 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.

Because CONTOUR does not handle irregularly spaced data, this


routine only works for surfaces defined on a rectangular grid.
The matrices or vectors X and Y define the axis limits only.
See also 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.

Here are some examples:

AZ = -37.5, EL = 30 is the default 3-D view.


AZ = 0, EL = 90 is directly overhead and the default 2-D view.
AZ = EL = 0 looks directly up the first column of the matrix.
AZ = 180 is behind the matrix.

VIEW(2) sets the default 2-D view, AZ = 0, EL = 90.


VIEW(3) sets the default 3-D view, AZ = -37.5, EL = 30.

[AZ,EL] = VIEW returns the current azimuth and elevation.

VIEW(T) accepts a 4-by-4 transformation matrix, such as


the perspective transformations generated by VIEWMTX.

T = VIEW returns the current general 4-by-4 transformation


matrix.

See also VIEWMTX, the AXES properties View, Xform.

» 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 :3-D shaded surface graph.

» 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

SURFL 3-D shaded surface with lighting.


SURFL(...) is the same as SURF(...) except that it draws the
surface with highlights from a light source.

SURFL(Z), SURFL(X,Y,Z), SURFL(Z,S), and SURFL(X,Y,Z,S) are all


legal. S, if specified, is the three vector S = [Sx,Sy,Sz]
that specifies the direction of the light source. S can also be
specified in spherical coordinates, S = [AZ,EL].

The shading is based on a combination of diffuse, specular and


ambient lighting models.

The default value for S is 45 degrees counterclockwise from


the current view direction. Use CLA, HOLD ON, VIEW(AZ,EL),
SURFL(...), HOLD OFF to plot the lighted surface with view
direction (AZ,EL).

The relative contributions due to ambient light, diffuse


reflection, specular reflection, and the specular spread
coefficient can be set by using five arguments
SURFL(X,Y,Z,S,K) where K=[ka,kd,ks,spread].

Relies on the ordering of points in the X,Y, and Z matrices


to define the inside and outside of parametric surfaces.
Try SURFL(X',Y',Z') if you don't like the results of
this function. Due to the way surface normal vectors are
computed, SURFL requires matrices that are at least 3-by-3.

See also SURF.

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

slice(V,sx,sy,sz,nx) draws slices of volume V at the locations specified in the index


vectors sx, sy, and sz. nx is the number of rows in volume array V.

» [x,y,z] = meshgrid(-2:.2:2, -2:.2:2, -2:.2:2);


» v = exp(-x.^2 - y.^2 - z.^2);
» slice(x,y,z,v,[10 21],21,[1 10],21),colormap(gray);

-1

-2
2
1 2
0 1
0
-1 -1
-2 -2

NOTE: colormap(map) sets the current figure's colormap to map.


Color maps:
hsv - Hue-saturation-value color map.
gray - Linear gray-scale color map.
hot - Black-red-yellow-white color map.
cool - Shades of cyan and magenta color map.
bone - Gray-scale with a tinge of blue color map.
copper - Linear copper-tone color map.
pink - Pastel shades of pink color map.
prism - Prism color map.
jet - A variant of HSV.

34
flag - Alternating red, white, blue, and black color map.

NOTE: print -dpcx16 filename saves graph to pcx file.

NOTE: close closes the current figure window.

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;

Example: diff(sin(x.^2))/h is an approximation to 2*cos(x.^2).*x

» 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.

z = trapz(x,y) computes the integral of y with respect to x using trapezoidal


integration. x and y must be vectors of the same length,or x must be a column
vector and y a matrix with as many rows as x. trpaz computes the integral of each
column of y separately.The resulting z is a scalar or a row vector.

» 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

Ordinary Differential Equations:

» 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.

The result can be displayed by: plot(tout, yout).

See also ODE45, ODEDEMO.

for more information about M-files see Programming Language section.

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('F',x1,x2) attempts to return a value of x which is a local minimizer of F(x) in the


interval x1 < x < x2. 'F' is a string containing the name of the objective function to be
minimized.

» fmin('cos',3,4)
ans =
3.1416

fzero(F,X) finds a zero of f(x). F is a string containing the name of a real-valued


function of a single real variable.X is a starting guess.The value returned is near a
point where F changes sign.

» 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.

See also TYPE, ECHO.

» help function

FUNCTION Function M-files.


New functions may be added to MATLAB's vocabulary if they
are expressed in terms of other existing functions. The
commands and functions that comprise the new function must
be put in a file whose name defines the name of the new
function, with a filename extension of '.m'. At the top of
the file must be a line that contains the syntax definition
for the new function. For example, the existence of a file
on disk called STAT.M with:

function [mean,stdev] = stat(x)


n = length(x);
mean = sum(x) / n;
stdev = sqrt(sum((x - mean).^2)/n);

defines a new function called STAT that calculates the


mean and standard deviation of a vector. The variables
within the body of the function are all local variables.
See SCRIPT for procedures that work globally on the work-
space.

See also ECHO, SCRIPT.

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 = find(X) returns the indices of the vector X that are non-zero.


For example, I = find(A>100), returns the indices of A where A is greater than
100.

[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

isempty(X) returns 1 if X is an empty matrix and 0 otherwise.An empty matrix has a


zero size in at least one dimension,for example 0-by-0, 0-by-5, etc.
» isempty([pi NaN Inf -Inf])
ans =
0

isreal(X) returns 1 if all elements in X have zero imaginary part.


» isreal([pi NaN Inf -Inf])
ans =
1

isglobal(A) is 1 if A is a global variable, 0 otherwise.


» isglobal('y')
ans =
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 variable = expr, statement, ..., statement END

The columns of the expression are stored one at a time in


the variable and then the following statements, up to the
END, are executed. The expression is often of the form X:Y,
in which case its columns are simply scalars. Some examples
(assume N has already been assigned a value).

FOR I = 1:N,
FOR J = 1:N,
A(I,J) = 1/(I+J-1);
END
END

FOR S = 1.0: -0.1: 0.0, END steps S with increments of -0.1


FOR E = EYE(N), ... END sets E to the unit N-vectors.

» help while
WHILE Repeat statements an indefinite number of times.
The general form of a WHILE statement is:

WHILE variable, statement, ..., statement, END

The statements are executed while the variable has all


non-zero elements. The variable is usually the result of
expr rop expr where rop is ==, <, >, <=, >=, or ~=.
For example (assuming A already defined):

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.

INPUT('What is your name','s') gives the prompt in the text


string and waits for character string input. The typed input
is not evaluated; the characters are simply returned as a
MATLAB string.

» 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:

----- Choose a color -----

1) Red
2) Blue
3) Green

Select a menu number:


The number entered by the user in response to the prompt is
returned. On machines that support it, the local menu system
is used. The maximum number of menu items is 32.
» help pause
PAUSE Wait for user response.
PAUSE causes a procedure to stop and wait for the user to
strike any key before continuing.
PAUSE(n) pauses for n seconds before continuing.

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.

MATLAB as a programming language:


» help eval
EVAL Execute string containing MATLAB expression.
EVAL(s), where s is a string, causes MATLAB to execute
the string as an expression or statement.

EVAL(s1,s2) provides the ability to catch errors. It


executes string s1 and returns if the operation was
successful. If the operation generates an error,
string s2 is evaluated before returning. Think of this
as EVAL('try','catch')

[X,Y,Z,...] = EVAL(s) returns output arguments from the


expression in string s.

The input strings to EVAL are often created by


concatenating substrings and variables inside square
brackets. For example:

Generate a sequence of matrices named M1 through M12:

for n = 1:12
eval(['M' num2str(n) ' = magic(n)'])
end

Run a selected M-file script. The strings making up


the rows of matrix D must all have the same length.

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.

For an example, see the functions TIC and TOC.

See also ISGLOBAL, CLEAR, WHO.

» help nargchk
NARGCHK Check number of input arguments.
Return error message if not between low and high.
If it is, return empty matrix.

9.Character String Functions


General.
strings - About character strings in MATLAB.

abs - Convert string to numeric values.


» abs('123')
ans =
49 50 51

setstr - Convert numeric values to string.


» setstr(ans)
ans =
123

isstr - True for string.


» isstr('matlab')
ans =
1

blanks - String of blanks.


» ['a' blanks(2) 'b']
ans =
a b

deblank - Remove trailing blanks.


» deblank(['a' 0 0 'b' 32 32 32])
ans =
ab

str2mat - Form text matrix from individual strings.


» str2mat('row1','row2')
ans =
row1
row2

eval - Execute string with MATLAB expression.


» eval(['eye' '(2)'])
ans =
1 0
0 1

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

upper - Convert string to uppercase.


» upper('a')
ans =
A

lower - Convert string to lowercase.


» lower(ans)
ans =
a

isletter - True for letters of the alphabet.


» isletter('+')
ans =
0

isspace - True for white space characters.


» isspace(' ')
ans =
1

strrep - Replace a string with another.


» s1='This is a good example';
» strrep(s1,'good','great')
ans =
This is a great example

» 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

int2str - Convert integer to string.

44
» int2str(12.5)
ans =
12

str2num - Convert string to number.


» str2num('12')
ans =
12

Hexadecimal to number conversion.


hex2dec - Convert hex string to decimal integer.
» hex2dec('aa')
ans =
170
dec2hex - Convert decimal integer to hex string.
» dec2hex(79)
ans =
4F

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.

s =date returns a string containing the date in dd-mmm-yy format.

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]

Here's an example of using etime to time an operation:


t0 = clock;
operation
etime(clock,t0)
The sequence of commands
tic
any stuff
toc
prints the time required for the stuff.

Managing commands and functions:

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;

lookfor - Keyword search through the HELP entries.


which - Locate functions and files.

path - Control MATLAB's search path.


» help path
PATH Control MATLAB's directory search path.
PATH, by itself, prettyprints MATLAB's current search path.
The search path list originates as the environment variable
MATLABPATH in the underlying operating system, or is set by
MATLABRC, and is perhaps individualized by STARTUP.

P = PATH returns a string containing the path in P.


PATH(P) changes the path to P.
PATH(P1,P2) changes the path to the concatenation of the
two path strings P1 and P2. Thus PATH(PATH,P) appends
a new directory to the current path and PATH(P,PATH)
prepends a new path. If P1 or P2 are already on the path,
they are not added.
For example, the following statements add another directory
to MATLAB's search path:

DOS: path(P,'TOOLS\GOODSTUFF')
See also GETENV, WHAT, CD, DIR.

Working with files and the operating system:


cd - Change current working directory.
dir - Directory listing.
delete - Delete file.
! - Execute operating system command.
» !copy fun.m c:

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.

disp - Display matrix or text.


» disp('Enjoy MATLAB!')
Enjoy MATLAB!

References
®
[1] D.M.Etter,Engineering Problem Solving with MATLAB ,Prentice Hall,1997
®
[2] MATLAB Reference Guide,The MathWorks,Inc,1992

47

You might also like