MATLAB is a wonderful environment for serious numerical (and symbolic) computations as well as for graphics. It is replacing FORTRAN and other languages that have often been used for numerical scientific computations.
TOPICS
Primers and Introductions
Primers and Introductions
The following text materials are recommended for your use in learning MATLAB. Subsequent pages of this primer provide a summary of key features of the language.
-
R. Pratap, Getting Started with MATLAB 6, Oxford University Press, New York, 2002. Inexpensive; excellent intro & Language Reference Summary [this is a recommended text for ENGRD 241].
-
William J. Palm, Introduction to MATLAB 6 for Engineers, McGraw-Hill, 2001.
-
Edward B. Magrab, An Engineer’s Guide to MATLAB, Prentice Hall, Upper Saddle River, NJ, 2000.
Getting Started
This version of MATLAB starts up with several windows:
Launch Pad lists the components of MATLAB available. We will focus primarily on MATLAB but might use some of the Toolboxes as well.
Workspace lists all active variables, their matrix dimension, the amount of memory being used, and the variable class. It is updated with each change to a variable or addition of a new variable.
Command History lists all commands input to the command window in sequence. It is updated with each command input.
Current Directory indicates where MATLAB is currently looking for and saving files. MATLAB files in that directory are listed.
Command Window is where MATLAB receives commands from the user. Commands can be mathematical operations, requests for information about MATLAB capabilities (help), names of instruction files (M-files), etc.
Getting Help
MATLAB has several options for on-line assistance.
MATLAB
offers a tutorial, which can be accessed from the
Help menu or by typing ‘demo’ at the command prompt. It would be a good idea to run through some of these demos to get an idea of how MATLAB does “stuff”!
The index of MATLAB help information can be accessed from
Help -> MATLAB Help. Here you can find information on getting started, using MATLAB, and implementing built-in functions. Information on the built-in functions may also be obtained by using the commands ‘help’ and ‘lookfor’ in the command window. ‘help
functionname’ provides help on the function if you know its exact name (i.e., it looks for the
functionname.
m file). If you don’t know the exact name of the function, use ‘lookfor
keyword’ to get a list of functions with string
keyword in their description.
The MATLAB Home Page is located at http://www.mathworks.com/products/matlab .
File Management and Miscellaneous Commands
dir directory of files in disk
delete filename delete file from disk
type filename list file in disk
diary filename saves the diary of a session (like a transcript of the command history plus any command window outputs)
load filename load variables stored in a file
save filename save variables as an .MAT-file
what show M-files and MAT-files on disk
who shows variables in memory
whos shows variables and sizes (just like in the workspace window)
clear var1 var2 ... releases the variables from memory; releases ALL variables if none are specifically identified
clc clears the command screen
; separate rows and avoids printing to screen
% comment; does not execute the line
^C aborts any job inside MATLAB
exit or quit exits MATLAB
pwd shows current working directory
mkdir creates directory
path gets or sets MATLAB path (just like in the current directory window)
dir/ls lists content of current directory (just like in the current directory window)
Assigning Variable Values
MATLAB initializes new variables whenever they are first used in a program or session. Values are assigned with the equals symbol.
A = 5
The program is case sensitive, so A is not the same variable as a.
Creating Matrices and Arrays
The colon operator is used to form row and column vectors from matrices. Suppose we have a (6x6) matrix A. Then B = A(:,6) will form a column vector containing elements in the sixth column of A. We could also form row and columns vectors containing elements in order, for example:
H = 1:8
will form a vector containing numbers 1 through 8, or
H = 1:2:9
forms a vector containing numbers 1 through 9 with increments of 2. Hence,
H = [1 3 5 7 9]
To form an array use a semicolon between rows; for a 4 by 3 matrix
A one could use:
A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ; 10:12 ],
or
A = [ u ; v ]
where u and v are row vectors. A(2,4) refers to the element in the 2nd row and 4th column of
A.
B = A(1:3, 2:3)
creates a new matrix B from the 1st through 3rd rows, and 2nd through 3rd columns of A.
Special Matrices
The following commands will create special matrices, or perform special matrix functions.
ones(n) or ones(m,n) creates a matrix of ones of size (nxn) or (mxn)
zeros(n) or zeros(m,n) creates matrix of zeros of size (nxn) or (mxn)
eye(n) creates identity matrix
diag(v) creates diagonal matrix with diagonal elements from vector v
diag(A) creates a vector containing diagonal of matrix A
trace(A) equals sum(diag(A)) which equals the trace of A
tril(A),triu(A) extract the lower/upper triangular part of a matrix
size(A) gives dimensions of the matrix
reshape(A,m,n) transforms A into a mn matrix
(total # entries must remain unchanged)
A’ gives transpose of A
rot90(A) rotates A by 90
fliplr(A) flips A from left to right
flipud(A) flips A from up to down
Matrix and Array Operators
Matrix operators
|
Operation
|
Array operator
|
+
|
addition
|
+
|
-
|
subtraction
|
-
|
*
|
multiplication
|
.*
|
/
|
right division
|
./
|
\
|
left division
|
.\
|
^
|
power
|
.^
|
Matrix operations include the traditional matrix multiplication, C = A*B =
Array operations are performed element-by-element so that A * B = (a
ij*b
ij).
Use of array operations can result in efficient code that avoids the use of loops.
Other Operations include Kronecker tensor product (kron), and matrix and array power.
For a complete list on the special matrices type ‘help specmat’ at the prompt.
Graphing
In order to produce a graph both variables need to have the same number of points.
You can use any of the following commands:
plot(x,y) produce a linear x-y plot
loglog(x,y) produce a loglog x-y plot
semilogx(x,y) produce a semilog x-y plot
semilogy(x,y) produce a semilog y-x plot
There are several other plotting functions that are easy to use for plotting graphs
fplot takes the function of a single variable and plots it between two given limits
ezplot this is a function from the symbolic toolbox and is probably the easiest way to make simple plots
funtool this is a two screen plotting calculator that does symbolic calculations
One can insert text into graphs using
title('text') text appears as the title on top of a plot
xlabel('text') text appears as the label for the x axis
ylabel('text') text appears as the label for the y axis
Other useful commands are:
grid toggles grid on/off the graph
hold holds the screen for subsequent plots
shg shows the graph window as the active
clf clears the graph window
print prints graphics/figure window
For online help type “help graph2d” for 2D plots and “help graph3d” for 3D plots
Interactive Input/Output Functions
disp(' text ') displays text in command window
x = input(' prompt ') displays the prompt on screen and waits for value to be entered
pause M-file execution stops and waits until any key is pressed
menu creates a onscreen menu
Special Values
Note: These values can be overwritten in a program or session (i.e., i = 5 will change the value). The special value is restored with the “clear” command.
eps machine epsilon
pi 3.1415926....
i or j square root of -1
Mathematical Functions
Trig: sin, cos, tan, cot, sec, csc, asn, acos, atan, tan2, acot, asec, acsc, sinh, cosh, coth, sech, ...
Exponential: exp, log, log10, sqrt
Complex: abs, real, imag, conj, angle
Round off functions: fix, floor, ceil, round, rem, sign
Special math: bessel, besselh, beta, betain, ellipj, ellipke, erf, erfinv, gamma, gammainc, log2, rat
Statistics: mean, median, std, min, max, prod, cumprod, sum cumsum, sort, cov, corrcoef, hist
Relational operators
<
|
less than
|
<=
|
less or equal than
|
>
|
greater than
|
>=
|
greater or equal than
|
==
|
equal
|
~=
|
not equal
|
Logical operators
-
&
|
Logical AND
|
|
|
Logical OR
|
~
|
Logical NOT
|
xor
|
Exclusive OR
|
Control Flow Statements
FOR ------ for m = array % here array is a set of indices
statements
...
end
for m = 0:2:24
sum = sum+m; % sum even integers from 0 to 24
end
WHILE --- while expression
statements
end
IF ----- if expression
statements
end
if-else-if-- if expression
statements
elseif expression
statements
...
else
statements
...
end
MATLAB Programs (M-files)
At this time you may wonder if working in MATLAB is just entering one command at a time. The answer is NO. You can actually write MATLAB programs, so you don't have to type things over and over. A MATLAB program, called an M-file, is just a list (or series) of MATLAB commands, the same commands that you can use interactively in the command window. You can write that list of commands in a text file and then execute the program from the command window.
To create an M-file, start MATLAB and under the
File menu select
New and
M-file. Type your commands in the M-file window. Store the M-file with the same name as the function, and with the suffix ".M" such as "Prog.M". The file can be stored and run from a floppy or the hard disk. After you have changed an M-file, remember to save it before using the function or script. MATLAB uses the saved version of the program, and not the version displayed in the window.
MATLAB programs in M-files can be classified into two groups:
script files and
function files. They differ in two things: (i) the way you execute them, and (ii) the type of variables they involve.
Script files
Script files are M-files that can be executed by typing their names in the command window, or calling them from other M-files. The variables they contain or define are global variables. That is, after you execute a script file all variables involved would be in memory and usable from the command window.
Function files
Function files are M-files whose variables are defined locally. Unless defined otherwise, after you execute a function file you won't have access to those variables. Almost all commands in MATLAB are examples of function files. Function files have arguments and outputs, which must be specified in order to execute the function. The first line of a function file must be of the following format:
function [ x,y ] = Prog(a,b,c)
where x and y are values/vectors/arrays that are returned, and
a, b, c are values/vectors/arrays that are passed to the function.
Note: The name of the function M-file must be the same as the name of the function. One executes a function by typing its name with arguments and outputs in the command window, or by calling it when executing another M-file. We can execute the function defined above from the command window by typing:
[ z1,z2 ] = Prog(15,45,-3);
MATLAB FUNCTIONS FOR NUMERICAL METHODS
Function Function Description
Approximation, Errors, and Operation Counts
eps a permanent variable = machine epsilon (floating-point rel. accuracy)
realmax largest possible floating-point number
realmin smallest possible floating-point number
Roots of Equations
fzero determines the roots of a function of one variable
roots determines the roots of a polynomial
Systems of Linear Algebraic Equations
x = A\c solution of Ax = c where A is square and x and c are column vectors
balance diagonal scaling to increase eigenvalue accuracy
chol computes the Cholesky factorization of a positive definite matrix
cond computes the 2-norm condition number of a matrix
det computes the determinant of a square matrix
eig computes the eigenvalues and eigenvectors of a matrix
inv computes the inverse of a square matrix
lu computes an LU matrix decomposition
norm computes the norm of a matrix or vector (1-, 2-, or infinity-norm)
rank calculates the rank of a matrix (number of linearly independent rows)
rcond estimates the reciprocal of the 1-norm condition number of a matrix
Curve Fitting: Regression
polyfit computes a least squares polynomial
Curve Fitting: Interpolation
interp1 performs linear/spline/cubic interpolation with a 1D table
interp2 performs linear/cubic interpolation with a 2D table
spline interpolates using a (clamped) cubic spline, or use interp1
Optimization
fgoalattain solves the multi-objective goal attainment optimization problem
Numerical Integration
quad numerical integration with adaptive recursive Simpson's Rule
quadl numerical integration with adaptive recursive Lobatto quadrature
trapz numerical integration with the Trapezoidal Rule
Numerical Differentiation
del2 five-point discrete Laplacian (Laplace's PDE in 2D)
diff computes the differences between adjacent elements
diff(x)./diff(y) approximates derivatives dy/dx by differences
Solution of ODE's
ode23 solves an ordinary differential equation with 2nd & 3rd order RK
ode45 solves an ordinary differential equation with 4th & 5th
order RK