This is not the document you are looking for? Use the search form below to find more!

Report home > Computer / Internet

An Introduction to Matlab

3.00 (13 votes)
Document Description
by David F. Griffiths Matlab is an interactive system for doing numerical computations. Matlab relieves you of a lot of the mundane tasks associated with solving problems numerically. This allows you to spend more time thinking, and encourages you to experiment.
File Details
  • Added: September, 11th 2008
  • Reads: 707
  • Downloads: 155
  • File size: 1.64mb
  • Pages: 37
  • Tags: matlab, introduction, numerical computation
  • content preview
Submitter
  • Username: desantis
  • Name: desantis
  • Documents: 37
Embed Code:

Add New Comment




Related Documents

Financial Accounting An Introduction to Concepts Methods and Uses Stickney 13th Edition Solutions Manual

by: gordonbarbier, 48 pages

Financial Accounting An Introduction to Concepts Methods and Uses Stickney 13th Edition Solutions Manual

An Introduction to Management Science Quantitative Approach to Decision Making Anderson Sweeney Williams 13th Edition Test Bank

by: georgesheslers, 49 pages

An Introduction to Management Science Quantitative Approach to Decision Making Anderson Sweeney Williams 13th Edition Test Bank

An Introduction to Management Science Quantitative Approach to Decision Making Anderson Sweeney Williams 13th Edition Solutions Manual

by: georgesheslers, 50 pages

An Introduction to Management Science Quantitative Approach to Decision Making Anderson Sweeney Williams 13th Edition Solutions Manual

An Introduction to Management Science Quantitative Approach to Decision Making Anderson Sweeney Williams 13th Edition Test Bank

by: georgesheslers, 49 pages

An Introduction to Management Science Quantitative Approach to Decision Making Anderson Sweeney Williams 13th Edition Test Bank

An Introduction to Management Science Quantitative Approach to Decision Making Anderson Sweeney Williams 13th Edition Test Bank

by: georgesheslers, 49 pages

An Introduction to Management Science Quantitative Approach to Decision Making Anderson Sweeney Williams 13th Edition Test Bank

An Introduction To Java Web Technology

by: igino, 40 pages

An Introduction to Java Web Technology (Java Servlet) Presented At: JECRC, Faculty of E&T, Jodhpur National University, Jodhpur, Rajasthan India -342001 HTTP HTTP ...

Understanding Media and Culture: An Introduction to Mass Communication, v. 1.0, Jack Lule, ISBN: 978-1-4533-2918-4, T E S T B A N K

by: smplustb, 107 pages

Most Complete Test Bank for Understanding Media and Culture: An Introduction to Mass Communication, v. 1.0, Jack Lule, ISBN: 978-1-4533-2918-4, E-mail Me:: smplustb@gmail.com E-mail Me:: ...

An Introduction to Matlab Version 2.3 (MatLab Notes)

by: manualzon, 37 pages

Free to download matlab ebook/tutorial on introduction to matlab, a perfect companion for Matlab Guide ebook. Inside you will find matlab at a glance including Numbers & Formats, Variables, ...

an introduction to Quantum Mechanics

by: Milad, 4 pages

this pdf document is an easy-to-understand introduction to quantum mechanics.

An Introduction to Partial Differential Equations with MATLAB (Chapman & Hall/Crc Applied Mathematics & Nonlinear Science) by Matthew P. Coleman

by: loes, 2 pages

An Introduction to Partial Differential Equations with MATLAB (Chapman & Hall/Crc Applied Mathematics & Nonlinear Science) by Matthew P. Coleman ...

Content Preview
An Introduction to Matlab
Version 2.3
David F. Gri?ths
Department of Mathematics
The University
Dundee DD1 4HN
With additional material by Ulf Carlsson
Department of Vehicle Engineering
KTH, Stockholm, Sweden
Copyright c 1996 by David F. Gri?ths. Amended October, 1997, August 2001, September 2005.
This introduction may be distributed provided that it is not be altered in any way and that its source
is properly and completely speci?ed.

Contents
15 Examples in Plotting
13
1
MATLAB
2
16 Matrices—Two–Dimensional Arrays
13
16.1 Size of a matrix . . . . . . . . . . . .
14
2
Starting Up
2
16.2 Transpose of a matrix . . . . . . . .
14
2.1
Windows Systems
. . . . . . . . . .
2
16.3 Special Matrices
. . . . . . . . . . .
14
2.2
Unix Systems . . . . . . . . . . . . .
2
16.4 The Identity Matrix . . . . . . . . .
14
2.3
Command Line Help . . . . . . . . .
2
16.5 Diagonal Matrices
. . . . . . . . . .
15
2.4
Demos . . . . . . . . . . . . . . . . .
3
16.6 Building Matrices . . . . . . . . . . .
15
16.7 Tabulating Functions . . . . . . . . .
15
3
Matlab as a Calculator
3
16.8 Extracting Bits of Matrices . . . . .
16
16.9 Dot product of matrices (.*) . . . .
16
4
Numbers & Formats
3
16.10Matrix–vector products
. . . . . . .
16
5
Variables
3
16.11Matrix–Matrix Products . . . . . . .
17
5.1
Variable Names . . . . . . . . . . . .
3
16.12Sparse Matrices . . . . . . . . . . . .
17
6
Suppressing output
4
17 Systems of Linear Equations
18
17.1 Overdetermined system of linear equa-
7
Built–In Functions
4
tions . . . . . . . . . . . . . . . . . .
18
7.1
Trigonometric Functions . . . . . . .
4
7.2
Other Elementary Functions . . . . .
4
18 Characters, Strings and Text
20
8
Vectors
4
19 Loops
20
8.1
The Colon Notation . . . . . . . . .
5
20 Logicals
21
8.2
Extracting Bits of a Vector . . . . .
5
20.1 While Loops . . . . . . . . . . . . . .
22
8.3
Column Vectors . . . . . . . . . . . .
5
20.2 if...then...else...end . . . . . .
23
8.4
Transposing . . . . . . . . . . . . . .
5
21 Function m–?les
23
9
Keeping a record
6
21.1 Examples of functions . . . . . . . .
24
10 Plotting Elementary Functions
6
22 Further Built–in Functions
25
10.1 Plotting—Titles & Labels . . . . . .
7
22.1 Rounding Numbers . . . . . . . . . .
25
10.2 Grids . . . . . . . . . . . . . . . . . .
7
22.2 The sum Function . . . . . . . . . . .
25
10.3 Line Styles & Colours . . . . . . . .
7
22.3 max & min . . . . . . . . . . . . . . .
26
10.4 Multi–plots . . . . . . . . . . . . . .
7
22.4 Random Numbers
. . . . . . . . . .
26
10.5 Hold . . . . . . . . . . . . . . . . . .
7
22.5 find for vectors . . . . . . . . . . . .
27
10.6 Hard Copy
. . . . . . . . . . . . . .
8
22.6 find for matrices . . . . . . . . . . .
27
10.7 Subplot . . . . . . . . . . . . . . . .
8
10.8 Zooming . . . . . . . . . . . . . . . .
8
23 Plotting Surfaces
27
10.9 Formatted text on Plots . . . . . . .
8
10.10Controlling Axes . . . . . . . . . . .
9
24 Timing
28
11 Keyboard Accelerators
9
25 On–line Documentation
29
12 Copying to and from Word and other
26 Reading and Writing Data Files
29
applications
10
26.1 Formatted Files . . . . . . . . . . . .
30
12.1 Window Systems . . . . . . . . . . .
10
26.2 Unformatted Files
. . . . . . . . . .
30
12.2 Unix Systems . . . . . . . . . . . . .
10
27 Graphic User Interfaces
31
13 Script Files
10
28 Command Summary
32
14 Products, Division & Powers of Vec-
tors
11
14.1 Scalar Product (*) . . . . . . . . . .
11
14.2 Dot Product (.*) . . . . . . . . . . .
11
14.3 Dot Division of Arrays (./) . . . . .
12
14.4 Dot Power of Arrays (.^) . . . . . .
12
1

1
MATLAB
• from the separate Help window found under
the Help menu or
• Matlab is an interactive system for doing nu-
merical computations.
• from the Matlab helpdesk stored on disk or
on a CD-ROM.
• A numerical analyst called Cleve Moler wrote
the ?rst version of Matlab in the 1970s. It
Another useful facility is to use the ’lookfor keyword’
has since evolved into a successful commercial
command, which searches the help ?les for the key-
software package.
word. See Exercise 16.1 (page 17) for an example
of its use.
• Matlab relieves you of a lot of the mundane
tasks associated with solving problems nu-
2.2
Unix Systems
merically. This allows you to spend more time
thinking, and encourages you to experiment.
• You should have a directory reserved for sav-
ing ?les associated with Matlab. Create such
• Matlab makes use of highly respected algo-
a directory (mkdir) if you do not have one.
rithms and hence you can be con?dent about
Change into this directory (cd).
your results.
• Start up a new xterm window (do xterm & in
• Powerful operations can be performed using
the existing xterm window).
just one or two commands.
• Launch Matlab in one of the xterm windows
• You can build up your own set of functions
with the command
for a particular application.
• Excellent graphics facilities are available, and
matlab
the pictures can be inserted into LATEX and
After a short pause, the logo will be shown
Word documents.
followed by a window containing the Matlab
These notes provide only a brief glimpse of the
interface. Should you wish to run Matlab in
power and ?exibility of the Matlab system. For a
an xterm window, use the command
more comprehensive view we recommend the book
matlab -nojvm
Matlab Guide
D.J. Higham & N.J. Higham
and, following dislpay of the logo, the Matlab
SIAM Philadelphia, 2000, ISBN: 0-89871-469-9.
prompt >> will appear.
Type quit at any time to exit from Mat-
lab.
2
Starting Up
2.1
Windows Systems
2.3
Command Line Help
Help is available from the command line prompt.
On Windows systems MATLAB is started by double- Type
clicking the MATLAB icon on the desktop or by
help help for “help” (which gives a brief syn-
opsis of the help system),
selecting MATLAB from the start menu.
help for a list of topics.
The ?rst few lines of this read
The starting procedure takes the user to the Com-
mand window where the Command line is indicated
with ’>>’. Used in the calculator mode all Matlab
HELP topics:
commands are entered to the command line from
the keyboard.
matlab/general -
General purpose commands.
Matlab can be used in a number of di?erent ways or
matlab/ops
-
Operators and special char...
modes; as an advanced calculator in the calculator
matlab/lang
-
Programming language const...
mode, in a high level programming language mode
matlab/elmat
-
Elementary matrices and ma...
and as a subroutine called from a C-program. More
matlab/elfun
-
Elementary math functions.
matlab/specfun -
Specialized math functions.
information on the ?rst two of these modes is given
below.
(truncated lines are shown with . . . ).
Then to ob-
Help and information on Matlab commands can be
tain help on “Elementary math functions”, for instance,
found in several ways,
type
• from the command line by using the ’help >> help elfun
topic’ command (see below),
2

This gives rather a lot of information so, in order to see
Command
Example of Output
the information one screenful at a time, ?rst issue the
>>format short
31.4162(4–decimal places)
command more on, i.e.,
>>format short e
3.1416e+01
>>format long e
3.141592653589793e+01
>> more on
>>format short
31.4162(4–decimal places)
>> help elfun
>>format bank
31.42(2–decimal places)
Hit any key to progress to the next page of information.
2.4
Demos
format—how Matlab prints numbers—is controlled by
the “format” command. Type help format for full list.
Demonstrations are invaluable since they give an indi-
Should you wish to switch back to the default format
cation of Matlabs capabilities. A comprehensive set are
then format will su?ce.
available by typing the command
The command
>> demo
format compact
is also useful in that it suppresses blank lines in the
( Warning: this will clear the values of all current vari-
output thus allowing more information to be displayed.
ables.)
5
Variables
3
Matlab as a Calculator
>> 3-2^4
The basic arithmetic operators are + - * / ^ and these
ans =
are used in conjunction with brackets: ( ). The symbol
-13
^ is used to get exponents (powers): 2^4=16.
>> ans*5
You should type in commands shown following
ans =
the prompt: >>.
-65
>> 2 + 3/4*5
The result of the ?rst calculation is labelled “ans” by
ans =
Matlab and is used in the second calculation where its
5.7500
value is changed.
>>
We can use our own names to store numbers:
Is this calculation 2 + 3/(4*5) or 2 + (3/4)*5? Mat-
>> x = 3-2^4
lab works according to the priorities:
x =
1. quantities in brackets,
-13
2. powers 2 + 3^2 ?2 + 9 = 11,
>> y = x*5
y =
3. * /, working left to right (3*4/5=12/5),
-65
4. + -, working left to right (3+4-5=7-5),
so that x has the value ?13 and y = ?65. These can
Thus, the earlier calculation was for 2 + (3/4)*5 by
be used in subsequent calculations. These are examples
priority 3.
of assignment statements: values are assigned to
variables. Each variable must be assigned a value before
4
Numbers & Formats
it may be used on the right of an assignment statement.
Matlab recognizes several di?erent kinds of numbers
5.1
Variable Names
Type
Examples
Legal names consist of any combination of letters and
digits, starting with a letter. These are allowable:
Integer
1362, ?217897
Real
1.234, ?10.76
?
NetCost, Left2Pay, x3, X3, z25c5
Complex
3.21 ? 4.3i (i =
?1)
These are not allowable:
Inf
In?nity (result of dividing by 0)
NaN
Not a Number, 0/0
Net-Cost, 2pay, %x, @sign
Use names that re?ect the values they represent.
The “e” notation is used for very large or very small
Special names: you should avoid using
numbers:
eps = 2.2204e-16 = 2?54 (The largest number such
-1.3412e+03 = ?1.3412 × 103 = ?1341.2
that 1 + eps is indistinguishable from 1) and
-1.3412e-01 = ?1.3412 × 10?1 = ?0.13412
pi = 3.14159... = ?.
All computations in MATLAB are done in double pre-
If you wish to do arithmetic with complex numbers,both
?
cision, which means about 15 signi?cant ?gures. The
i and j have the value
?1 unless you change them
3

>> i,j, i=3
>> x = 9;
ans = 0 + 1.0000i
>> sqrt(x),exp(x),log(sqrt(x)),log10(x^2+6)
ans = 0 + 1.0000i
ans =
i
= 3
3
ans =
8.1031e+03
6
Suppressing output
ans =
1.0986
One often does not want to see the result of intermedi-
ans =
ate calculations—terminate the assignment statement
1.9395
or expression with semi–colon
exp(x) denotes the exponential function exp(x) = ex
>> x=-13; y = 5*x, z = x^2+y
and the inverse function is log:
y =
-65
>> format long e, exp(log(9)), log(exp(9))
z =
ans = 9.000000000000002e+00
104
ans = 9
>>
>> format short
the value of x is hidden. Note also we can place several
and we see a tiny rounding error in the ?rst calculation.
statements on one line, separated by commas or semi–
log10 gives logs to the base 10. A more complete list
colons.
of elementary functions is given in Table 2 on page 32.
Exercise 6.1 In each case ?nd the value of the expres-
sion in Matlab and explain precisely the order in which
8
Vectors
the calculation was performed.
These come in two ?avours and we shall ?rst describe
i)
-2^3+9
ii)
2/3*3
row vectors: they are lists of numbers separated by ei-
iii)
3*2/3
iv)
3*4-5^2*2-3
ther commas or spaces. The number of entries is known
v)
(2/3^2*5)*(3-4^3)^2
vi)
3*(3*4-2*5^2-3) as the “length” of the vector and the entries are often
referred to as “elements” or “components” of the vec-
7
Built–In Functions
tor.The entries must be enclosed in square brackets.
>> v = [ 1 3, sqrt(5)]
7.1
Trigonometric Functions
v =
1.0000
3.0000
2.2361
Those known to Matlab are
>> length(v)
sin, cos, tan
ans =
and their arguments should be in radians.
3
e.g. to work out the coordinates of a point on a circle of
radius 5 centred at the origin and having an elevation
Spaces can be vitally important:
30o = ?/6 radians:
>> v2 = [3+ 4 5]
>> x = 5*cos(pi/6), y = 5*sin(pi/6)
v2 =
x =
7
5
4.3301
>> v3 = [3 +4 5]
y =
v3 =
2.5000
3
4
5
The inverse trig functions are called asin, acos, atan
We can do certain arithmetic operations with vectors
(as opposed to the usual arcsin or sin?1 etc.).
The
of the same length, such as v and v3 in the previous
result is in radians.
section.
>> acos(x/5), asin(y/5)
>> v + v3
ans = 0.5236
ans =
ans = 0.5236
4.0000
7.0000
7.2361
>> pi/6
>> v4 = 3*v
ans = 0.5236
v4 =
3.0000
9.0000
6.7082
7.2
Other Elementary Functions
>> v5 = 2*v -3*v3
v5 =
These include sqrt, exp, log, log10
-7.0000
-6.0000
-10.5279
>> v + v2
??? Error using ==> +
Matrix dimensions must agree.
4

i.e. the error is due to v and v2 having di?erent lengths.
>> r5(3:6)
A vector may be multiplied by a scalar (a number—
ans =
see v4 above), or added/subtracted to another vector
5
-1
-3
-5
of the same length. The operations are carried out
elementwise.
To get alternate entries:
We can build row vectors from existing ones:
>> r5(1:2:7)
>> w
= [1 2 3],
z = [8 9]
ans =
>> cd = [2*z,-w], sort(cd)
1
5
-3
-7
w =
What does r5(6:-2:1) give?
1
2
3
See help colon for a fuller description.
z =
8
9
cd =
8.3
Column Vectors
16
18
-1
-2
-3
These have similar constructs to row vectors. When
ans =
de?ning them, entries are separated by ; or “newlines”
-3
-2
-1
16
18
>> c = [ 1; 3; sqrt(5)]
Notice the last command sort’ed the elements of cd
c =
into ascending order.
1.0000
We can also change or look at the value of particular
3.0000
entries
2.2361
>> c2 = [3
>> w(2) = -2, w(3)
4
w =
5]
1
-2
3
c2 =
ans =
3
3
4
5
8.1
The Colon Notation
>> c3 = 2*c - 3*c2
This is a shortcut for producing row vectors:
c3 =
-7.0000
>>
1:4
-6.0000
ans =
-10.5279
1
2
3
4
so column vectors may be added or subtracted pro-
>> 3:7
vided that they have the same length.
ans =
3
4
5
6
7
>> 1:-1
8.4
Transposing
ans =
We can convert a row vector into a column vector (and
[]
vice versa) by a process called transposing—denoted by
More generally a : b : c produces a vector of entries
’.
starting with the value a, incrementing by the value b
>> w, w’, c, c’
until it gets to c (it will not produce a value beyond c).
w =
This is why 1:-1 produced the empty vector [].
1
-2
3
>> 0.32:0.1:0.6
ans =
ans =
1
0.3200
0.4200
0.5200
-2
>> -1.4:-0.3:-2
3
ans =
c =
-1.4000
-1.7000
-2.0000
1.0000
3.0000
8.2
Extracting Bits of a Vector
2.2361
ans =
>>
r5 = [1:2:6, -1:-2:-7]
1.0000
3.0000
2.2361
r5 =
>> t = w + 2*c’
1
3
5
-1
-3
-5
-7
t =
3.0000
4.0000
7.4721
To get the 3rd to 6th entries:
>> T = 5*w’-2*c
T =
3.0000
5

-16.0000
v2
1 by 2
2
16
Full
No
10.5279
v3
1 by 3
3
24
Full
No
v4
1 by 3
3
24
Full
No
If x is a complex vector, then x’ gives the complex con-
x
1 by 1
1
8
Full
No
jugate transpose of x:
y
1 by 1
1
8
Full
No
>> x = [1+3i, 2-2i]
Grand total is 16 elements using 128 bytes
ans =
1.0000 + 3.0000i
2.0000 - 2.0000i
>> x’
10
Plotting Elementary Func-
ans =
1.0000 - 3.0000i
tions
2.0000 + 2.0000i
Suppose we wish to plot a graph of y = sin 3?x for
Note that the components of x were de?ned without
0 ? x ? 1. We do this by sampling the function at
a * operator; this means of de?ning complex numbers
a su?ciently large number of points and then joining
works even when the variable i already has a numeric
up the points (x, y) by straight lines. Suppose we take
value. To obtain the plain transpose of a complex num-
N + 1 points equally spaced a distance h apart:
ber use .’ as in
>> N = 10; h = 1/N; x = 0:h:1;
>> x.’
ans =
de?nes the set of points x = 0, h, 2h, . . . , 1 ? h, 1. Alter-
1.0000 + 3.0000i
nately, we may use the command linspace: The gen-
2.0000 - 2.0000i
eral form of the command is linspace (a,b,n) which
generates n + 1 equispaced points between a and b, in-
clusive. So, in this case we would use the command
9
Keeping a record
>> x = linspace (0,1,11);
Issuing the command
The corresponding y values are computed by
>> diary mysession
>> y = sin(3*pi*x);
will cause all subsequent text that appears on the screen
to be saved to the ?le mysession located in the direc-
and ?nally, we can plot the points with
tory in which Matlab was invoked. You may use any
>> plot(x,y)
legal ?lename except the names on and off. The record
may be terminated by
The result is shown in Figure 1, where it is clear that
the value of N is too small.
>> diary off
The ?le mysession may be edited with your favourite
editor (the Matlab editor, emacs, or even Word) to re-
move any mistakes.
If you wish to quit Matlab midway through a calcula-
tion so as to continue at a later stage:
>> save thissession
will save the current values of all variables to a ?le
called thissession.mat. This ?le cannot be edited.
When you next startup Matlab, type
>> load thissession
and the computation can be resumed where you left o?.
A list of variables used in the current session may be
seen with
Figure 1: Graph of y = sin 3?x for 0 ? x ? 1 using
>> whos
h = 0.1.
See help whos and help save.
On changing the value of N to 100:
>> whos
>> N = 100; h = 1/N; x = 0:h:1;
Name
Size Elements
Bytes
Density Complex
>> y = sin(3*pi*x);
plot(x,y)
ans
1 by 1
1
8
Full
No
v
1 by 3
3
24
Full
No
we get the picture shown in Figure 2.
v1
1 by 2
2
16
Full
No
6

The number of available plot symbols is wider than
shown in this table. Use help plot to obtain a full
list. See also help shapes.
10.4
Multi–plots
Several graphs may be drawn on the same ?gure as in
>> plot(x,y,’w-’,x,cos(3*pi*x),’g--’)
A descriptive legend may be included with
>> legend(’Sin curve’,’Cos curve’)
which will give a list of line–styles, as they appeared
in the plot command, followed by a brief description.
Matlab ?ts the legend in a suitable position, so as not
Figure 2: Graph of y = sin 3?x for 0 ? x ? 1 using to conceal the graphs whenever possible.
h = 0.01.
For further information do help plot etc.
The result of the commands
10.1
Plotting—Titles & Labels
>> plot(x,y,’w-’,x,cos(3*pi*x),’g--’)
To put a title and label the axes, we use
>> legend(’Sin curve’,’Cos curve’)
>> title(’Multi-plot ’)
>> title(’Graph of y = sin(3pi x)’)
>> xlabel(’x axis’),
ylabel(’y axis’)
>> xlabel(’x axis’)
>> grid
>> ylabel(’y-axis’)
is shown in Figure 3. The legend may be moved man-
The strings enclosed in single quotes, can be anything
ually by dragging it with the mouse.
of our choosing.
Some simple LATEX commands are
available for formatting mathematical expressions and
Greek characters—see Section 10.9.
See also ezplot the “Easy to use function plotter”.
10.2
Grids
A dotted grid may be added by
>> grid
This can be removed using either grid again, or grid
off.
10.3
Line Styles & Colours
The default is to plot solid lines. A solid white line is
produced by
Figure 3: Graph of y = sin 3?x and y = cos 3?x for
>> plot(x,y,’w-’)
0 ? x ? 1 using h = 0.01.
The third argument is a string whose ?rst character
speci?es the colour(optional) and the second the line
style. The options for colours and styles are:
10.5
Hold
A call to plot clears the graphics window before plot-
Colours
Line Styles
ting the current graph. This is not convenient if we
y
yellow
.
point
wish to add further graphics to the ?gure at some later
m
magenta
o
circle
stage. To stop the window being cleared:
c
cyan
x
x-mark
r
red
+
plus
>> plot(x,y,’w-’), hold on
g
green
-
solid
>> plot(x,y,’gx’), hold off
b
blue
*
star
w
white
:
dotted
“hold on” holds the current picture; “hold off” re-
k
black
-.
dashdot
leases it (but does not clear the window, which can be
--
dashed
done with clf). “hold” on its own toggles the hold
state.
7

10.6
Hard Copy
factor of two.
This may be repeated to any desired
level.
To obtain a printed copy select Print from the File
Clicking the right mouse button will zoom out by a
menu on the Figure toolbar.
factor of two.
Alternatively one can save a ?gure to a ?le for later
Holding down the left mouse button and dragging the
printing (or editing).
A number of formats is avail-
mouse will cause a rectangle to be outlined. Releasing
able (use help print to obtain a list). To save a ?le
the button causes the contents of the rectangle to ?ll
in “Encapsulated PostScript” format, issue the Matlab
the window.
command
zoom off turns o? the zoom capability.
print -deps fig1
Exercise 10.1 Draw graphs of the functions
which will save a copy of the image in a ?le called
y
=
cos x
fig1.eps.
y
=
x
10.7
Subplot
for 0 ? x ? 2 on the same window. Use the zoom fa-
cility to determine the point of intersection of the two
The graphics window may be split into an m × n array
curves (and, hence, the root of x = cos x) to two signif-
of smaller windows into which we may plot one or more
icant ?gures.
graphs. The windows are counted 1 to mn row–wise,
starting from the top left. Both hold and grid work on
The command clf clears the current ?gure while close
the current subplot.
1 will close the window labelled “Figure 1”. To open
>> subplot(221), plot(x,y)
a new ?gure window type figure or, to get a window
>>
xlabel(’x’),ylabel(’sin 3 pi x’)
labelled “Figure 9”, for instance, type figure (9). If
>> subplot(222), plot(x,cos(3*pi*x))
“Figure 9” already exists, this command will bring this
>>
xlabel(’x’),ylabel(’cos 3 pi x’)
window to the foreground and the result subsequent
>> subplot(223), plot(x,sin(6*pi*x))
plotting commands will be drawn on it.
>>
xlabel(’x’),ylabel(’sin 6 pi x’)
>> subplot(224), plot(x,cos(6*pi*x))
10.9
Formatted text on Plots
>>
xlabel(’x’),ylabel(’cos 6 pi x’)
It is possible to change to format of text on plots so
subplot(221) (or subplot(2,2,1)) speci?es that the
as to increase or decrease its size and also to typeset
window should be split into a 2 × 2 array and we select
simple mathematical expressions (in LATEX form).
the ?rst subwindow.
We shall give two illustrations.
First we plot the ?rst 100 terms in the sequence {xn}
n
given by xn = 1 + 1
and then graph the function
n
?(x) = x3 sin2(3?x) on the interval ?1 ? x ? 1. The
commands
>> set(0,’Defaultaxesfontsize’,16);
>> n = 1:100;
x = (1+1./n).^n;
>> subplot (211)
>> plot(n,x,’.’,[0 max(n)],exp(1)*[1 1],...
’--’,’markersize’,8)
>> title(’x_n = (1+1/n)^n’,’fontsize’,12)
>> xlabel(’n’), ylabel(’x_n’)
>> legend(’x_n’,’y = e^1 = 2.71828...’,4)
>> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> subplot (212)
>> x = -2:.02:2; y = x.^3.*sin(3*pi*x).^2;
>> plot(x,y,’linewidth’,2)
>> legend(’y = x^3sin^2 3\pi x’,4)
10.8
Zooming
>> xlabel(’x’)
We often need to “zoom in” on some portion of a plot
produce the graph shown below. The salient features
in order to see more detail. Clicking on the “Zoom in”
of these commands are
or “Zoom out” button on the Figure window is simplest
1. The ?rst line increases the size of the default font
but one can also use the command
size used for the axis labels, legends and titles.
>> zoom
2. The size of the plot symbol “.” is changed from
the default (6) to size 8 by the additional string
Pointing the mouse to the relevant position on the plot
followed by value “’markersize’,8”.
and clicking the left mouse button will zoom in by a
8

3. The strings x_n are formatted as xn to give sub-
The axis command has four parameters, the ?rst two
scripts while x^3 leads to superscripts x3.
are the minimum and maximum values of x to use on
Note also that sin23?x translates into the Matlab
the axis and the last two are the minimum and maxi-
command sin(3*pi*x).^2—the position of the
mum values of y. Note the square brackets. The result
exponent is di?erent.
of these commands is shown in Figure 4. Look at help
axis and experiment with the commands axis equal,
4. Greek characters ?, ?, . . . , ?, ? are produced by
axis verb, axis square, axis normal, axis tight in
the strings ’\alpha’, ’\beta’, . . . ,’\omega’, ’\Omega’. any order.
the integral symbol:
is produced by ’\int’.
5. The thickness of the line used in the lower graph
is changed from its default value (0.5) to 2.
6. Use help legend to determine the meaning of
the last argument in the legend commands.
One can determine the current value of any plot prop-
erty by ?rst obtaining its “handle number” and then
using the get command such as
>> handle = plot (x,y,’.’)
>> get (handle,’markersize’)
ans =
6
Experiment also with set (handle) (which will list
possible values for each property) and
set(handle,’markersize’,12)
which will increase the size of the marker (a dot in this
Figure 4: The e?ect of changing the axes of a plot.
case) to 12. Also, all plot properties can be edited from
the Figure window by selecting the Tools menu from
the toolbar.
For instance, to change the linewidth
11
Keyboard Accelerators
of a graph, ?rst select the curve by double clicking
(it should then change its appearance) and then select
One can recall previous Matlab commands by using the
Line Properties. . .
from the Tools . This will pop
? and ? cursor keys. Repeatedly pressing ? will review
up a dialogue window from which the width, colour,
the previous commands (most recent ?rst) and, if you
style,. . . of the curve may be changed.
want to re-execute the command, simply press the re-
turn key.
To recall the most recent command starting with p, say,
type p at the prompt followed by ?. Similarly, typing
pr followed by ? will recall the most recent command
starting with pr.
Once a command has been recalled, it may be edited
(changed). You can use ? and ? to move backwards
and forwards through the line, characters may be in-
serted by typing at the current cursor position or deleted
using the Del key. This is most commonly used when
long command lines have been mistyped or when you
want to re–execute a command that is very similar to
one used previously.
The following emacs–like commands may also be used:
cntrl a
move to start of line
cntrl e
move to end of line
10.10
Controlling Axes
cntrl f
move forwards one character
cntrl b
move backwards one character
Once a plot has been created in the graphics window
cntrl d
delete character under the cursor
you may wish to change the range of x and y values
shown on the picture.
Once you have the command in the required form, press
>> clf, N = 100; h = 1/N; x = 0:h:1;
return.
>> y = sin(3*pi*x); plot(x,y)
Exercise 11.1 Type in the commands
>> axis([-0.5 1.5 -1.2 1.2]),
grid
9

Download
An Introduction to Matlab

 

 

Your download will begin in a moment.
If it doesn't, click here to try again.

Share An Introduction to Matlab to:

Insert your wordpress URL:

example:

http://myblog.wordpress.com/
or
http://myblog.com/

Share An Introduction to Matlab as:

From:

To:

Share An Introduction to Matlab.

Enter two words as shown below. If you cannot read the words, click the refresh icon.

loading

Share An Introduction to Matlab as:

Copy html code above and paste to your web page.

loading