Introduction To Matlab: Luke Dickens
Introduction To Matlab: Luke Dickens
Introduction
The Basics
Built-in Functions
Plotting
Overview
Matlab is an intuitive, easy-to-learn, high performance language for numerical computation and data visualisation. It can handle: Numerical mathematics and computation Algorithm development Data acquisition Modelling, simulations, and prototyping Data analysis, exploration, and visualisation Scientic and engineering graphics Application development, incl. graphical user interfaces MATLAB stands for MATrix LABoratory. Its basic variable is arrays, i.e. vectors and matrices. Matlab also has many built-in functions, as well as specialised add-on tool boxes. Unlike other mathematical packages, such as MAPLE or MATHEMATICA, MATLAB cannot perform symbolic manipulations without the use of additional Toolboxes.
The language
High-level language based on arrays, functions, input/output, and ow statements (for, if, while)
Graphics
Data plotting in 2d and 3d, as well as image analysis and animation tools
External interfaces
Interaction between C and Fortran programs with Matlab, either for linking convenient routines from Matlab in C/Fortran, or for Matlab to call fast C/Fortran programs
Interactive mode
just type commands and dene variables, empty workspace with command clear
Simple scripts
M-le (name.m) with list of commands Operate on existing data in work space, or create new data Variables remain in workspace (until cleared) Re-useable
M-le functions
M-le as with scripts May return values Re-usable Easy to call from other functions (make sure le is in Matlab search path)
Introduction
The Basics
Built-in Functions
Plotting
Variables
Variables do not need to be declared. Simply assign values to variable names, e.g.
x = [1 2 3 4 5] x = 1 2 3 4 5
For quiet assignment, terminate expression with a semi-colon. To display a variable, simply use the variable name on its own.
x = [1 2 3 4 5]; x x = 1 2 3 4 5
Vectors
Matlab distinguishes between row and column vectors. x dened on the previous slide is a row vector use spaces or commas (,) to separate entries. To dene column vector, use semi-colons (;) to separate entries (rows), e.g.
y = [6; 7; 8; 9; 10]
A dot product is a row vector multiplied by (*) a column vector, e.g. x*y, y*x, x*x or y*y. What happens when we multiply a column vector by a row vector, e.g. y*x?
More on Vectors
Create a natural integer sequence (vector) by specifying the rst and the last element separated by a colon (:), e.g.
u = [0:8] u = 0 1 2 3 4 5 6 7 8
A number of elements can be referenced using the colon notation, e.g. v(1:3), u(2:2:6). What will these give?
Matrices
In fact, row vectors are simply 1 n matrices, and column vectors are n 1 matrices. We can dene more general matrices using spaces (or commas) to separate column entries, and semi-colons (or carraige return) to separate rows, e.g.
A=[1 2; 3 4;] is the 2 2 matrix B=[4 5; 6 7; 8 9;]
1 3 2 4 5 7 9
4 is the 3 2 matrix 6 8
Reference the ith-row jth-column element of matrix A, with A(i,j). We can even pull out a submatrix with the colon notation (just a colon gives the full row/column), e.g.
B(2:3,:) is the 2 2 matrix
6 8 7 9
Block Matrices
We can use vectors to build larger vectors by placing them in square parenthesis and separating them by spaces (commas), called horizontal concatenation, so
z=[x y] is the row vector
1 2 3 4 5 6 7 8 9 10
Likewise we can block together compatible matrices to build larger matrices. What will [A B] and [A ; B] produce?
Scalar Operations
We can multiply every element of a matrix by a scalar, e.g. 3*A, with the obvious results. So if r a real number, and is
D is the matrix
d11 . . . dm1 ... .. . ... d1n . . . dmn ... .. . ...
then
r*D
r d1n . . . r dmn
Similarly, if we add or subtract a scalars and matrices together, e.g. A+3 or 1-B, then the same scalar operation is applied to each element in the matrix.
then
D+E
is the matrix
... .. . ...
but
B+C ??? Error using ==> plus Matrix dimensions must agree.
We also have elementwise multiply (.*) and divide (./). With elementwise division, be careful that there are no zero elements in the second matrix. Why? The elementwise power operator (.^), applies a power to each element of a matrix.
Matrix Multiplication
but
A*B ??? Error using ==> mtimes Inner matrix dimensions must agree.
Which of the following are valid: A*A, A*B, B*A? Can also take the power of any square matrix with the hat symbol (^), e.g. A^2 is equivalent to A*A.
Matrix Division
For a square invertable1 n n matrix M, and compatible vector b, we have the matrix equivalent of division,
a = M\b is the solution of the equation Ma = b a = b/M is the solution of the equation aM = b
More generally, see the eig built in function. 1: A matrix M Rnn is invertible, if x Rn Mx = 0 x = 0
addition subtraction multiplication power left division right division elementwise multiplication elementwise power elementwise left division elementwise right division transpose
Comparison Operators
As with addition and subtraction. Relational operators can be applied to a scalar and a scalar; a matrix and a scalar; or to two matrices of the same dimension. The following are available: < less than > greater than <= less than or equal >= greater than or equal == equal ~= not equal Boolean values (or matrices) may be connected by the following logical operators. & and | or ~ not You will explore these in the lab.
Introduction
The Basics
Built-in Functions
Plotting
Built-in Functions
There are numerous built-in functions (i.e. commands) in MATLAB. There is only room here to describe a few of them. We separate them roughly into categories. Special Functions: help: Displays help information for any MATLAB command. lookfor: A keyword search function. Useful for nding unknown commands. who: Lists the current variables in the workspace. whos: Lists current variables with detailed information. clear: Clears current variables. exit: Closes interactive mode. I strongly recommended you look up any built-in function with help before using them or see the online support at: http://www.mathworks.co.uk
Scalar Functions
Certain MATLAB functions are essentially used on scalars, but operate element-wise when applied to a matrix (or vector). They are summarized below (angles are in radians). sin trigonometric sine cos trigonometric cosine tan trigonometric tangent asin trigonometric inverse sine (arcsine) acos trigonometric inverse cosine (arccosine) atan trigonometric inverse tangent (arctangent) exp exponential log natural logarithm abs absolute value sqrt square root rem remainder round round towards nearest integer floor round towards negative innity ceil round towards positive innity
Vector Functions
Other MATLAB functions operate essentially on vectors returning a scalar value. Some of these functions are given in the table below. max largest component min smallest component length length of a vector sort sort in ascending order sum sum of elements prod product of elements median median value mean mean value std standard deviation
for a vector of 101 evenly spaced points in the range [, ]. We can achieve the same results with the linspace(a,b,n) command, where a and b give the two endpoints and n gives the number of elements, e.g.
x1 = linspace(-pi,pi,101)
Similarly, to generate n logarithmically spaced elements from 10a to 10b , type logspace(a,b,n), e.g.
x2 = logspace(0,3,4)
Operations on Matrices
Some commands that can be applied to matrices. size size of a matrix det determinant of a square matrix inv inverse of a matrix rank rank of a matrix rref reduced row echelon form eig eigenvalues and eigenvectors poly characteristic polynomial norm norm of matrix (1-norm, 2-norm, -norm) cond condition number in the 2-norm lu LU factorization qr QR factorization chol Cholesky decomposition svd singular value decomposition Again, you will get a chance to explore some of these matrix functions yourselves in the lab.
Introduction
The Basics
Built-in Functions
Plotting
To plot the cosine function, begin by choosing the points along the x-axis, to evaluate cos(x).
x=-pi:0.01:pi;
Smaller increments give a smoother curve. Then dene the corresponding y values,
y = cos(x);
The plot appears in a separate window. For more details, you should read the help page on plot.
The third argument, for the colour, appears within single quotes. We can get a dashed line instead of a solid one with
plot(x,y,--)
. o x + * : -. --
Multiple Plots
Multiple curves can appear on the same graph. To show this, we dene another vector
z = sin(x);
we can get both graphs on the same axis, distinguished by their line type, using
plot(x,y,r-,x,z,b:)
This gives a plot with the red dashed line for y = cos(x) and a blue dotted line for z = sin(x). The command legend provides a legend (or key) to help distinguish multiple plots, e.g.
legend(cos(x),sin(x))
subplot loglog semilogx semilogy errorbar bar hist surf surfl mesh
Using subplot
The subplot command allows you to plot two curves alongside one another. An example is
x = linspace(0,5,51); subplot(2,1,1) plot(x,sin(x),-) axis([0 5 -2 2]) title(A sine wave) subplot(2,1,2) plot(x,sin(x)+0.1*randn(1,51),o) title(Noisy points on the sine wave.)
The command randn is used to generate a random vector with elements sampled from N(0, 1) the normal distribution.
A Surface Plot
A Quick Example of a 3-D Plot is given below:
[x,y] = meshgrid(-3:.1:3,-3:.1:3); z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ... 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ... 1/3*exp(-(x+1).^2 - y.^2); surf(z) xlabel(x) ylabel(y) zlabel(z) title(Peaks)
The command meshgrid species the 2 dimensional grid of points on which to evaluate the function. The ellipsis (...) allows for line continuation.
Saving Plots
Plots can be saved by clicking on the appropriate icon on the display, but if you would like to perform this at the command line then you can. To do this you need to get a handle to the gure you will create, then plot the graph, before nally passing the gure handle to the print function. The print command also needs to know the le type and le name. For example, the following commands will plot the sine function to le myplot.eps.
x = linspace(0,5,100); handle = figure; plot(x,sin(x)) print(handle,-deps,myplot.eps);
Summary
Overview of Matlab Vector and matrix construction Working with vectors and matrices Commonly used built in functions. Including: Special functions Operations on scalars, vector and matrices A focus on plotting
References
This course has been partly developed from material found in the following sources.
Getting Started with MATLAB7: A quick introduction for