Week 1: MATLAB BASICS

advertisement
Week 1: MATLAB BASICS
********************************** LECTURE 1 *************************
Goals for Class:
*
*
*
*
Learn how to access graphics version of Matlab
Learn about toolbar and windows features in Matlab
Learn about HELP facility
Run Matlab Demos to learn about general features
MATLAB ACCESS
MATLAB 7 is widely available at UNM, on both Windows and Linux
systems:
1. CIRT's Linux system and ESC South and DSH pods (Windows)
2. Dept of Math and Stat's Linux system and Windows based PCs in lab.
I believe that all of the systems also have the Statistics toolbox, which may
come in handy. The Linux versions can be run remotely, either in command mode
(with no graphics), or with graphics enabled, provided you have X-windows
capability on your machine.
You do not need to purchase MATLAB. However, if you choose to do so, you can get
a Student version for $99. The Statistics Toolbox costs an extra $59. See the
course webpage for link to Mathworks website. I have the impression that these
are fully functional versions of Matlab software, but I am not sure.
I use the WINDOWS (graphics) version of MATLAB, which has an interface that is
similar to that of other modern interactive software packages. If you plan to
run the LINUX version of MATLAB remotely, say from a laptop or desktop at home,
and then you need a connection, say through COMCAST, and software that will
allow you to run MATLAB at UNM but display graphics on your machine. Otherwise
you will be running the program in command mode. Two pieces of software that
allow you to remotely run X-window applications on either the UNM or Math/Stat
Linux systems are:
a. X-Win32 - for X-windows emulations, available for $15 from CIRT (see WINDOWS
software under Software Distribution). CAVEAT: you need a UNM purchase
requisition for this. Also available, but at higher cost from distributor:
www.starnet.com/products/xwin32
b. CYGWIN - FREE! but requires some guesswork on what parts of program that you
should download. During the installation process, you will be prompted for what
packages you wish to install (under a SELECT PACKAGES GUI). One of the packages
(NET) contains openssh files, which are important to select.
I downloaded CYGWIN to my laptop. To run CYGWIN remotely, I click the CYGWIN
icon on my desktop, and type startx at the $ prompt. A new window pops up in
which I type
ssh -X bedrick@ezra.math.unm.edu
which connects me to ezra, a machine on the Math/Stat LINUX system.
Perhaps someone can investigate the easiest way to install CYGWIN with
the necessary features and let the rest of us know.
RUNNING MATLAB
a. If you are on the Math/Stat LINUX system, type
% matlab7.2
to access the most recent version of Matlab.
b. If you are on the CIRT LINUX system, type
% matlab
c. If you are on the Math/Stat system and wish to run MATLAB on the
CIRT system, you first need to login, say
% ssh -X your_cirt_login@linux.unm.edu
then
% matlab
d. If you are running MATLAB remotely through CYGWIN, follow the steps
outlined above.
d. If you are running a personal copy of MATLAB on your machine, you
should know how to access it.
FIRST MATLAB SESSION
I will describe the structure of the MATLAB interface for the graphics
version, but will also show you some of the ways to get help in the
command version.
My version of Matlab runs with 4 windows visible:
Command Window: Allows you to specify Matlab commands to perform
data manipulations, run programs, etc. Numerical results are printed
in this window. Typing in a command to generate a plot will produce
a pop-up graphics window.
Command History Window: Chronicles list of commands you have used.
Clicking on a command in this window executes the command, and shows
result in Command Window (in the case of a plot, shows result in
a pop-up graphics window).
Workspace Window: Shows all scalars, vectors and matrices you have
defined in current session. Left clicking on an object using the
mouse opens an array editor that allows you to modify contents of
the object. Right clicking allows you to delete objects, among other
options.
Current Directory Window: Shows contents of current directory from
which programs can be run, data edited, etc.
Dropdown menus are available on the main toolbar, under options
FILE
EDIT
VIEW
DEBUG
DESKTOP
WINDOW
Help
(Allows data, programs, graphics to be imported)
(What windows do you wish to see?)
(Shows available help)
When you enter Matlab you will see the following in the command
window:
To get started, select MATLAB Help or Demos from the Help menu.
It is worth looking at the documentation that is available for
first time users (see this when you click on Matlab Help) and it
is worth exploring the Matlab demos.
You should also become familiar with the HELP utility. In the
graphics version, you will see that HELP is organized with a
standard help navigator, with tabs for Contents, Index, Search and
Demos. Under Contents, we have listings for Matlab and the available
toolboxes (for example, Statistics or Neural Networks). Clicking
on Matlab shows entries for Mathematics, Programming, Graphics,
Functions (alphabetical listing and by category), etc. Clicking on
Functions (alphabetical listing) shows all available functions.
Clicking on Mathematics shows information on Matrices, Polynomials
and Interpolation, etc. You need to learn how to learn this utility!
SOME HELP FEATURES
The information below will give you some idea on the detail for the
help facility, using commands typed in the command window. In the
graphics version, you can easily find this by navigating the options.
a. The Matlab prompt in the command window is >>
b. At the right hand side of several of the Matlab commands, I have a
<--- to describe to you what the command is doing. Do not do this
when you specify a command! This is not how comments are placed in
Matlab code (later)
>> more on
<--- output appears one window at time
keeps output from flying by
without being able to see it!
>> diary junk.1
<--- saves what you see in Command
Window in file junk.1 stored in
current directory.
>> help help
HELP Display help text in Command Window.
HELP, by itself, lists all primary help topics. Each primary
topic corresponds to a directory name on the MATLABPATH.
HELP / lists a description of all operators and special
characters.
HELP FUN displays a description of and syntax for the function
FUN. When FUN is in multiple directories on the MATLAB path,
HELP displays information about the first FUN found on the path
and lists PATHNAME/FUN for other (overloaded) FUNs.
HELP PATHNAME/FUN displays help for the function FUN in the
PATHNAME directory. Use this syntax to get help for overloaded
functions.
HELP DIR displays a brief description of each function in the
MATLAB directory DIR. DIR can be a relative partial pathname
(see HELP PARTIALPATH). When there is also a function called DIR,
help for both the directory and the function are provided.
HELP CLASSNAME.METHODNAME displays help for the method
METHODNAME of the fully qualified class CLASSNAME. To determine
CLASSNAME for METHODNAME, use CLASS(OBJ), where METHODNAME is of
the same class as the object OBJ.
HELP CLASSNAME displays help for the fully qualified class
CLASSNAME.
T = HELP('TOPIC') returns the help text for TOPIC as a string,
with each line separated by /n. TOPIC is any allowable argument
for HELP.
REMARKS:
1. Use MORE ON before running HELP to pause HELP output after a
screenful of text displays.
2. In the help syntax, function names are capitalized to make
them stand out. In practice, always type function names in
lowercase. For Java functions that are shown with mixed case
(for example, javaObject) type the mixed case as shown.
3. Use DOC FUN to display help about the function in the Help
browser, which might provide additional information, such as
graphics and examples.
4. Use DOC HELP for information about creating help for your own
M-files.
5. Use HELPBROWSER to access online documentation in the Help
browser. Use the Help browser Index or Search tabs to find more
information about TOPIC or other terms.
EXAMPLES:
help close - displays help for the CLOSE function.
help database/close - displays help for the CLOSE function
in the Database Toolbox.
help database - lists all functions in the Database Toolbox and
displays help for the DATABASE function.
help general - lists all functions in the directory
MATLAB/GENERAL.
help embedded.fi - displays help for the EMBEDDED.FI class in
the Fixed-Point Toolbox.
help embedded.fi.lsb displays help for the LSB method of the
EMBEDDED.FI class in the Fixed-Point Toolbox.
t = help('close') - gets help for the function CLOSE and stores
it as a string in t.
>> help
HELP topics
matlab\general
-
General purpose commands.
matlab\ops
-
Operators and special characters.
matlab\lang
-
Programming language constructs.
matlab\elmat
-
Elementary matrices and matrix manipulation.
matlab\elfun
-
Elementary math functions.
matlab\specfun
-
Specialized math functions.
matlab\matfun
-
Matrix functions - numerical linear algebra.
matlab\datafun
-
Data analysis and Fourier transforms.
....... cut out lots of things...........................
toolbox\stats
-
Statistics Toolbox
................
ETC ETC ETC
>> help stats
Statistics Toolbox
Version 5.0.2 (R14SP2) 21-Jan-2005
Distributions.
Parameter estimation.
betafit
- Beta parameter estimation.
binofit
- Binomial parameter estimation.
dfittool
- Distribution fitting tool.
evfit
- Extreme value parameter estimation.
expfit
- Exponential parameter estimation.
gamfit
- Gamma parameter estimation.
lognfit
- Lognormal parameter estimation.
mle
- Maximum likelihood estimation (MLE).
..................... ETC ETC ETC
Other broad areas in stat toolbox:
Probability density functions (pdf).
Cumulative Distribution functions (cdf).
Random Number Generators.
Statistics.
Likelihood functions.
Descriptive Statistics.
Linear Models.
Nonlinear Models.
Design of Experiments (DOE).
Statistical Process Control (SPC).
Multivariate Statistics.
Dimension Reduction Techniques.
Plotting.
Other Multivariate Methods.
Decision Tree Techniques.
Hypothesis Tests.
Distribution Testing.
Nonparametric Functions.
Hidden Markov Models.
Statistical Plotting.
Statistics Demos.
File Based I/O.
Utility Functions.
>> help tstat
TSTAT Mean and variance for the student's t distribution.
[MN,V] = TSTAT(NU) returns the mean and variance of
Student's T distribution with NU degrees of freedom.
>> help general
General purpose commands.
MATLAB Version 7.0.4 (R14SP2) 21-Jan-2005
General information.
syntax
- Help on MATLAB command syntax.
demo
- Run demonstrations.
ver
- MATLAB, Simulink and toolbox version information.
version
- MATLAB version information.
Managing the workspace.
who
- List current variables.
whos
- List current variables, long form.
clear
- Clear variables and functions from memory.
pack
- Consolidate workspace memory.
load
- Load workspace variables from disk.
save
- Save workspace variables to disk.
saveas
- Save Figure or model to desired output format.
memory
- Help for memory limitations.
recycle
- Set option to move deleted files to recycle folder.
quit
- Quit MATLAB session.
exit
- Exit from MATLAB.
Managing commands and functions.
what
- List MATLAB-specific files in directory.
type
open
which
pcode
mex
inmem
namelengthmax
-
List M-file.
Open files by extension.
Locate functions and files.
Create pre-parsed pseudo-code file (P-file).
Compile MEX-function.
List functions in memory.
Maximum length of MATLAB function or variable name.
..................... ETC ETC ETC
>> help ops
Operators and special characters.
Operators and special characters.
Arithmetic operators.
plus
- Plus
uplus
- Unary plus
minus
- Minus
uminus
- Unary minus
mtimes
- Matrix multiply
times
- Array multiply
mpower
- Matrix power
power
- Array power
mldivide
- Backslash or left matrix divide
mrdivide
- Slash or right matrix divide
ldivide
- Left array divide
rdivide
- Right array divide
kron
- Kronecker tensor product
Relational operators.
eq
- Equal
ne
- Not equal
lt
- Less than
gt
- Greater than
le
- Less than or equal
ge
- Greater than or equal
+
+
*
.*
^
.^
\
/
.\
./
kron
==
~=
<
>
<=
>=
Logical operators.
Short-circuit logical AND
&&
Short-circuit logical OR
||
and
- Element-wise logical AND
&
or
- Element-wise logical OR
|
not
- Logical NOT
~
xor
- Logical EXCLUSIVE OR
any
- True if any element of vector is nonzero
all
- True if all elements of vector are nonzero
..................... ETC ETC ETC
>> help elmat
Elementary matrices and matrix manipulation.
Elementary matrices.
zeros
- Zeros array.
ones
- Ones array.
eye
- Identity matrix.
repmat
- Replicate and tile array.
rand
- Uniformly distributed random numbers.
randn
- Normally distributed random numbers.
linspace
- Linearly spaced vector.
logspace
- Logarithmically spaced vector.
freqspace
- Frequency spacing for frequency response.
meshgrid
- X and Y arrays for 3-D plots.
accumarray - Construct an array with accumulation.
:
- Regularly spaced vector and index into matrix.
Basic array information.
size
- Size of array.
length
- Length of vector.
ndims
- Number of dimensions.
numel
- Number of elements.
disp
- Display matrix or text.
isempty
- True for empty array.
isequal
- True if arrays are numerically equal.
isequalwithequalnans - True if arrays are numerically equal.
Matrix manipulation.
cat
- Concatenate arrays.
reshape
- Change size.
diag
- Diagonal matrices and diagonals of matrix.
blkdiag
- Block diagonal concatenation.
tril
- Extract lower triangular part.
triu
- Extract upper triangular part.
..................... ETC ETC ETC
>> help elfun
Elementary math functions.
Trigonometric.
sin
sind
sinh
asin
asind
asinh
cos
cosd
cosh
-
Sine.
Sine of argument in degrees.
Hyperbolic sine.
Inverse sine.
Inverse sine, result in degrees.
Inverse hyperbolic sine.
Cosine.
Cosine of argument in degrees.
Hyperbolic cosine.
acos
acosd
acosh
tan
tand
tanh
Exponential.
exp
expm1
log
log1p
log10
log2
pow2
-
Inverse cosine.
Inverse cosine, result in degrees.
Inverse hyperbolic cosine.
Tangent.
Tangent of argument in degrees.
Hyperbolic tangent.
-
Exponential.
Compute exp(x)-1 accurately.
Natural logarithm.
Compute log(1+x) accurately.
Common (base 10) logarithm.
Base 2 logarithm and dissect floating point number.
Base 2 power and scale floating point number.
..................... ETC ETC ETC
>> diary off
<---- turns off output to junk.1
>> quit
<---- exit from command version of Matlab. In
Windows version (toolbar) FILE > EXIT
********************************** LECTURE 2 *************************
Goals for Class:
* Learn basic operators and vector/matrix input
Matlab allows for strings and numbers as data. We will emphasize
numerical data, which can be represented in decimal form, using scientific
notation, or as real and imaginary parts of complex numbers.
The basic operators are
+
*
/
\
^
'
( )
Addition
Subtraction
Multiplication
Division
Left array divide (later)
Exponentiation
Complex conjugate transpose or Conjugation
Specify order of operations
Matlab supports scalars, vectors, matrices, and high-order arrays. Elements can
be numbers or strings. Vectors can be either row vectors or column vectors. A
scalar is a 1-by-1 matrix while a vector is a matrix with 1 row or 1 column.
The discussion below focuses on commands that are entered in command
window.
MATLAB SESSION: MATRIX AND VECTOR INPUT + INDEXING
>> A = [1 2 3; 4 5 6; 7 8 9];
<- enter 3 by 3 matrix
; separates rows.
>> A
<- show elements of A
A =
1
4
7
2
5
8
3
6
9
>> A = [ 1 2 3
4 5 6
7 8 9 ]
<- linebreak inferred as new row
<- when semicolon is omitted at end
of command, Matlab echoes result
of the command
A =
1
4
7
2
5
8
3
6
9
>> size(A)
<- gives dimensions of A. result is not
assigned to new variable.
ans =
3
3
>> v = size(a);
<- assign dimensions to v
>> v
v =
3
3
>> m = [-1 6 3; 0 2 -3];
>> m
m =
<- enter 2 by 3 matrix
-1
0
6
2
3
-3
>> m(1,1)
<- show element in 1st row 1st col
ans =
-1
>> m(:,1)
<- 1st col of m
ans =
-1
0
>> q = m(2,:)
<- 2nd row of m
q =
0
2
-3
>> B=A';
<- B is A transpose
>> B
B =
1
2
3
4
5
6
7
8
9
>> x = [ 1 2 3]
<- enter 1 by 3 vector
x =
1
2
>> x'
3
<- transposed is a 3 by 1 vector
ans =
1
2
3
>> y = [1; 2; 3];
<- enter a 3 by 1 vector
>> y
ans =
1
2
3
>> xa = [-1.3 sqrt(3) (1+2+3)*4/5] <- elements can be functions of
numbers
xa =
-1.3000
1.7321
4.8000
>> xa(5) = abs(xa(1))
<- what is happening here?
xa =
-1.3000
1.7321
4.8000
>> x1 = 0:10
0
1.3000
<- row vector of = spaced values
x1 =
0
1
2
>> x2=[0: .1 : 10]';
>> x2
x2 =
0
0.1000
0.2000
0.3000
0.4000
0.5000
0.6000
.
.
.
9.4000
9.5000
9.6000
9.7000
9.8000
9.9000
10.0000
3
4
5
6
7
8
9
10
<- coln vector 0-10 increments of .1
>> size(x2)
ans =
101
1
>> length(x2)
<- length is size of vector!
ans =
101
>> xb = 1.2:4
<- what happens here?
xb =
1.2000
2.2000
3.2000
--- extension line
BASIC ARITHMETIC
A few things that have been defined:
>> x
<- row vector
x =
1
2
3
>> A
<- 3-by-3 matrix
A =
1
4
7
2
5
8
3
6
9
1
2
3
4
5
6
7
8
9
>> B
B =
>> y
y =
<- col vector
1
2
3
>> x + 2
<- can add or subtract numbers from
vectors or matrices (or other
numbers)
ans =
3
4
5
>> c = A - 4
c =
-3
0
3
-2
1
4
-1
2
5
>> C
<- Matlab is case sensitive!
??? Undefined function or variable 'C'.
>> A + B
<- can add or subtract matrices
with same dimensions
ans =
2
6
10
6
10
14
10
14
18
>> A - y
<- can not add or subtract when
vectors or matrices have different
dimensions
??? Error using ==> Matrix dimensions must agree.
>> A/4
<- can divide matrices or vectors
by scalars
ans =
0.2500
1.0000
1.7500
0.5000
1.2500
2.0000
0.7500
1.5000
2.2500
>> x/4
ans =
0.2500
0.5000
>> 3.0*A
0.7500
<- 3 is a constant so this
multiplies each element of A by 3
ans =
3
12
21
6
15
24
9
18
27
>> A*x
<- With vectors or matrices, *
attempts matrix multiplication.
Can't mult a 3-by-3 with a
1-by-3 matrix
Error using ==> *
Inner matrix dimensions must agree.
>> A*y
<- can mult a 3-by-3 with a 3-by-1
ans =
14
32
50
>> x*y
<- can mult a 1-by-3 with a 3-by-1
ans =
14
>> y*x
<- can mult a 3-by-1 with a 1-by-3
ans =
1
2
3
2
4
6
3
6
9
>> A*B
<- can mult a 3-by-3 with a 3-by-3
ans =
14
32
50
32
77
122
50
122
194
>> z = A \ y
<- left array divide solves A z = y
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 2.055969e-18
z =
-0.3333
0.6667
0
>> A^2
<- exponentiate A: same as A*A
ans =
30
66
102
36
81
126
42
96
150
>> A^2.3
<- what does this do?
ans =
1.0e+002 *
0.6755 + 0.0075i
1.5179 + 0.0008i
2.3603 - 0.0059i
0.8247 + 0.0020i
1.8645 + 0.0002i
2.9043 - 0.0016i
0.9740 - 0.0034i
2.2111 - 0.0004i
3.4482 + 0.0027i
ELEMENTWISE OPERATIONS
The use of a . before an operator (*, /, ^) allows elementwise
computations with vectors and matrices.
>> A
A =
1
4
7
2
5
8
3
6
9
1
2
3
4
5
6
7
8
9
>> B
B =
>> x
<- row vector
x =
1
2
3
>> y
<- col vector
y =
1
2
3
>> A.*B
<- elementwise multiplication of A and B
matrices must be same size
ans =
1
8
21
8
25
48
21
48
81
>> 2.*A
<- same as 2*A
ans =
2
8
14
4
10
16
6
12
18
>> x.*y
<- can't do this
Error using ==> .*
Matrix dimensions must agree.
>> x.*y'
<- this is OK
ans =
1
>>
4
9
C = ( 3.0*A - 2)/4
<- what does this do?
C =
0.2500
2.5000
4.7500
1.0000
3.2500
5.5000
1.7500
4.0000
6.2500
>> A.^2
<- elementwise exponentiation
not the same as A^2!
ans =
1
16
49
4
25
64
9
36
81
>> C = A./B
<- elementwise division. A and B
must have same dimensions.
C =
1.0000
2.0000
2.3333
0.5000
1.0000
1.3333
0.4286
0.7500
1.0000
>> C = A.^B
<- elementwise exponentiation. A and
B must have same dimensions
C =
1
16
343
16
3125
262144
2187
1679616
387420489
>> C = 1./A
<- what does this do?
C =
1.0000
0.2500
0.1429
0.5000
0.2000
0.1250
0.3333
0.1667
0.1111
>> A.^y
<- can't do it
Error using ==> .^
Matrix dimensions must agree.
>> x./y
<- can't do it
Error using ==> ./
Matrix dimensions must agree.
>> C = A + B - 4*(A.^B) - 7 + exp(A - B) + ...
- 4.*B - 7777
<- use ... at end of line to continue
statement (can have more than 3
dots and can repeat, as below)
>> C = A + B - 4*(A.^B) - 7 + exp(A - B) + ...
- 4.*B - 7777 ...
28*B + 564/6
Download