









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










MATLAB Tutorial written by Peter Blossey and James A. Rossmanith Department of Applied Mathematics University of Washington Seattle, WA
MATLAB (short for MATrix LABoratory) is a very useful piece of software for numerical analysis. It provides an environment for computation and visualization. Learning MATLAB is not the goal of this course, but a working knowledge of MAT- LAB will allow you to implement and test the algorithms that form the heart of this course. Seeing these algorithms at work will hopefully enable a deeper understand- ing of the mechanics, strengths and pitfalls of each algorithm.
Starting MATLAB
To start MATLAB, click on the MATLAB icon or type matlab at the command line prompt. To exit, type quit.
Entering Variables
There are three types of variables that you can use in matlab: scalars, vectors and matrices. To assign a value to a scalar variable, type
x = 0.
After hitting return, MATLAB will echo the value of the variable back to you:
x =
If you don’t want to see the value of the variable, add a semicolon at the end of the line:
x = 0.2;
To enter a vector or matrix, use square brackets to indicate the start and end of the vector/matrix. For example a row vector may be entered:
y = [ 0 1 2 3 4]
y =
0 1 2 3 4
To enter a variable with more than one row, the rows of the vector or matrix are separated by semicolons or by carriage returns. For example a column vector may be entered:
z = [ 0; 1; 2; 3; 4]
z =
0 1 2 3 4
A matrix may be entered similarly, with the rows of the matrix separated in this case by carriage returns and the whole expression enclosed in square brackets:
A = [ 0 2 3 7 12 8]
A =
0 2 3 7 12 8
The (complex conjugate) transpose of a vector or matrix may be obtained by placing an apostrophe after the expression:
w = z’
w =
0 1 2 3 4
B = A’
B =
0 3 12 2 7 8
To give a variable a set of evenly-spaced values, use the colon operator:
You may also select parts of a matrix or vector, using B(2,1:2) to specify the first two elements of the second row of B or B(2,:) for the entire second row of B.
B(2,:)
ans =
2 7 8
Often you need to access elements at or near the end of a vector. You can do this by typing y(end) or y(2:end) or y(2:end-1). This is very handy, especially when you want to plot part of a vector.
Getting information about variables
To see the size of a variable or its length (number of rows), type size(A) or length(A). To see all of the variables that are currently in the MATLAB workspace, type whos:
whos Name Size Bytes Class
A 3x2 48 double array B 2x3 48 double array ans 1x3 24 double array t 1x7 56 double array u 1x7 56 double array w 1x5 40 double array x 1x1 8 double array y 1x5 40 double array z 5x1 40 double array
Grand total is 45 elements using 360 bytes
Elementary computations
Variables may be added, subtracted, multiplied and divided as long as the rules of arithmetic and linear algebra are obeyed, i.e. you can’t divide by zero or multiply
a 1x2 matrix by a 3x4 matrix. Multiplying a vector or matrix by a scalar will scale each element of the vector or matrix by the value of the scalar.
v = 2*[1 2 3 4]
v =
2 4 6 8
Adding a scalar to a vector or matrix will add the value of the scalar to each element of the matrix:
D = 2+[1 2; 3 4]
D =
3 4 5 6
s = 2 + [0:5]
s =
2 3 4 5 6 7
Matrices and vectors may be added or subtracted as long as they are the same size. They may be multiplied as long as there are the same number of columns in the first as there are rows in the second.
s + 2*[0:5]
ans =
2 5 8 11 14 17
A*B
ans =
all commands within the loop. This can make the code much easier to read and understand.
If statements
MATLAB uses a similar structure for if statements:
if i == 1 DO SOMETHING elseif i == 2 DO SOMETHING ELSE elseif i == 3 DO SOMETHING ELSE else DO SOMETHING (IF i >= 4 or i <= 0) end
Plotting
To make a line plot of t versus
t, simply type:
plot(t,sqrt(t))
To make a plot to t versus
t and t versus t on the same plot, type
plot(t,sqrt(t),t,t)
putting each x-y pair together. You can add symbols or use symbols instead of lines by adding commands to each pair:
plot(t,sqrt(t),’*-’,t,t,’o-’)
See help plot for more information on plotting and a catalog of the available sym- bols and line types. Use legend(’sqrt(t)’,’t’) to label the different lines. Ti- tle your plot by typing title(’A plot of t versus sqrt(t)’). You can add labels to the axes similarly: xlabel(’t’) or ylabel(’sqrt(t)’). Other useful commands: axis, plot3 and (for a bit of fun) comet.
Clearing variables
You may clear a particular variable by typing
clear x
or all variables with
clear all
Formatting MATLAB output
By default, MATLAB outputs numbers with four digits after the decimal point. If one of the numbers is very large or all of them are very small, MATLAB uses scientific notation. However, the exponent is written only once at the beginning of the output, so be careful. For example:
[1 2 6 24 120 factorial(20)]
ans =
1.0e+18 *
0.0000 0.0000 0.0000 0.0000 0.0000 2.
To control the format of the output, type
format long e
for scientific notation with 15 digits. Other options include format short e, format short, format long, format short g. The default is format short.
Importing data
Use the load command to bring data into matlab from an external file:
load filename
Getting help
Type help followed by the name of the function. For example:
help plot
To get more help, try helpwin, helpdesk, demo or tour. Also, there is help avail- able on the Math Works website at
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.shtml.
ans = 0 0 1 0
You can even select sub-matrices in this way. Here we pick off a 3x3 matrix from the upper right corner of the identity matrix
I(1:3,2:4) ans = 0 0 0 1 0 0 0 1 0
Diagonals and triangles
Before introducing these, let’s create a 4x4 random matrix:
A = rand(4) A = 0.9501 0.8913 0.8214 0. 0.2311 0.7621 0.4447 0. 0.6068 0.4565 0.6154 0. 0.4860 0.0185 0.7919 0.
You can select the upper triangular part of A using triu:
upper = triu(A) upper = 0.9501 0.8913 0.8214 0. 0 0.7621 0.4447 0. 0 0 0.6154 0. 0 0 0 0.
The lower triangular part may be picked off using tril:
lower = tril(A) lower = 0.9501 0 0 0 0.2311 0.7621 0 0 0.6068 0.4565 0.6154 0 0.4860 0.0185 0.7919 0.
The main diagonal may be extracted (as a vector) using diag:
d = diag(A) d =
One can build matrices from diagonals. For example, useful matrices may be constructed from their diagonals:
D = diag([1 1 1 1],-1) D = 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0
D = D + diag([1 1 1 1],1) D = 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0
D = D - 2*eye(5) D = -2 1 0 0 0 1 -2 1 0 0 0 1 -2 1 0 0 0 1 -2 1 0 0 0 1 -
After constructing the matrix with the main diagonals, you may alter the first and last row if they differ from the rest:
D(1,1:4) = [2 -5 4 -1] D = 2 -5 4 -1 0 1 -2 1 0 0 0 1 -2 1 0 0 0 1 -2 1 0 0 0 1 -
Defn: M-files are MATLAB’s version of MAIN ROUTINES. All variables in an M-file script will still be there after you run it.
Although all the MATLAB commands can be run on the command line, for devel- oping code that is several lines long it is useful to write your program as an m-file script. I will show you how do to this below.
% This lets me add comments. % Please comment your code so that anyone % can easily see what you are doing
% Here is an example of a loop: j = 0; for i = 1: j = j + i; end
somefilename
NOTE: DO NOT USE THE NAME OF AN INTRINSIC MATLAB FUNCTION AS THE TITLE OF YOUR SCRIPT.
Defn: Functions are MATLAB’s version of SUBROUTINES. All variables in a func- tion are deleted after the function returns to them main routine.
% This is a sample function declaration function [out1,out2,out3] = somefunction(in1,in2)
% This lets me add comments. % Please comment your code so that anyone % can easily see what you are doing
% Here is an example of a loop: j = 0; for i = 1: j = j + i; end
[y1,y2,y3]=somefunction(x1,x2);
NOTE: DO NOT USE THE NAME OF AN INTRINSIC MATLAB FUNCTION AS THE TITLE OF YOUR FUNCTION.
In order to evaluate functions which are passed into a function we must utilize the feval function from MATLAB.
Example:
We would like to write a function that computes the slope of the line between the two points (a, f (a)) and (b, f (b)). Recall that the slope between these two points is give by
m =
f (b) − f (a) b − a
% slope.m - compute the slope between (a,f(a)) and (b,f(b))
function m = slope(func,a,b)
fa = feval(func,a); fb = feval(func,b);
m = (fb-fa)/(b-a);
slope(@fun,0.4,0.6)
ans =
-3.090169943749475e+