Professional Documents
Culture Documents
Executable Files
Matlab is a program that was originally designed
to simplify the implementation of numerical linear
algebra routines. It has since grown into An introduction is given on how to define
something much bigger, and it is used to files that contain command that matlab
implement numerical algorithms for a wide range can execute as if they had been typed in
of applications. The basic language used is very at the command prompt.
similar to standard linear algebra notation, but
there are a few extensions that will likely cause Subroutines
you some problems at first.
An introduction to subroutines is given.
The goal of the tutorials here is to provide a This is a more general way to provide an
simple overview and introduction to matlab. The executable file in which generic
tutorials are broken up into some of the basic arguments are passed back and forth
topics. The first includes a few examples of how through the command line.
Matlab makes it easy to create and manipulate
vectors. The tutorials move from the simple If statements
examples and lead to more complicated
examples. The basic control structure in matlab is the
"if" statement which allows for conditional
We have tutorials on the following subjects: execution of certain parts of a code. This
is useful when you have to check
Vectors conditions before deciding what actions
should be taken.
A basic introduction on how to define and
manipulate vectors in matlab. This is the Data Files
most basic way that numbers are stored
and accessed in matlab. Matlab allows a number of ways to access
data files for use in a session. The
Matrices different ways to save all of the data, a
particular matrix, and C style read write
An introduction on how to define and statements is examined. Also, the diary
manipulate matrices. We demonstrate command is examined to demonstrate
how to create matrices and how to access how a text copy of a session can be saved.
parts of a matrix.
Vector operations
Loops
Matlab is a software package that makes it easier Notice, though, that this always creates a row
for you to enter matrices and vectors, and vector. If you want to create a column vector you
manipulate them. The interface follows a need to take the transpose of a row vector. The
language that is designed to look a lot like the transpose is defined using an apostrophe ("'"):
notation use in linear algebra. In the following
tutorial, we will discuss some of the basics of
>> v = [3 1 7 -21 5 6]'
working with vectors.
v=
If you are running windows or Mac OSX, you can
start matlab by choosing it from the menu. To 3
start matlab on a unix system, open up a unix 1
shell and type the command to start the 7
software: matlab. This will start up the software, -21
and it will wait for you to enter your commands. 5
In the text that follows, any line that starts with 6
two greater than signs (>>) is used to denote the
matlab command line. This is where you enter
your commands.
A common task is to create a large vector with
numbers that fit a repetitive pattern. Matlab can
Almost all of Matlab's basic commands revolve define a set of numbers with a common
around the use of vectors. A vector is defined by increment using colons. For example, to define a
placing a sequence of numbers within square vector whose first entry is 1, the second entry is
braces: 2, the third is three, up to 8 you enter the
following:
>> v = [3 1]
>> v = = [1:8]
v=
v=
3 1
1 2 3 4 5 6 7 8
For the most part Matlab follows the standard You will need to be careful. These operations can
notation used in linear algebra. We will see later only be carried out when the dimensions of the
that there are some extensions to make some vectors allow it. You will likely get used to seeing
operations easier. For now, though, both addition the following error message which follows from
subtraction are defined in the standard way. For adding two vectors whose dimensions are
example, to define a new vector with the different:
numbers from 0 to -4 in steps of -1 we do the
following: >> u+v'
??? Error using ==> plus
>> u = [0:-1:4] Matrix dimensions must agree.
u = [0:-1:-4]
u= Matlab Tutorial
0 -1 -2 -3 -4 Introduction to Matrices in
Matlab
We can now add u and v together in the standard
way: A basic introduction to defining and manipulating
matrices is given here. It is assumed that you
>> u+v know the basics on how to define and manipulate
vectors using matlab.
ans =
0 1 2 3 4
1. Defining
Matrices
2. Matrix
Functions
Additionally, scalar multiplication is defined in the 3. Matrix
standard way. Also note that scalar division is Operations
defined in a way that is consistent with scalar
multiplication: Defining Matrices
0 2 4 6 8
ans =
>> A*v(1:3)
??? Error using ==> * 1.0e+15 *
Inner matrix dimensions must agree.
-2.7022 4.5036 -1.8014
>> A*v(1:3)' 5.4043 -9.0072 3.6029
-2.7022 4.5036 -1.8014
ans =
>> inv(a)
Get used to seeing that particular error message! ??? Undefined function or variable a.
Once you start throwing matrices and vectors
Other operations include finding an given below. It is left as an exercise for you to
approximation to the eigen values of a matrix. figure out which one is doing what.
There are two versions of this routine, one just
finds the eigen values, the other finds both the >> v = [1 3 5]'
eigen values and the eigen vectors. If you forget
which one is which, you can get more information v=
by typing help eig at the matlab prompt.
1
>> eig(A) 3
5
ans =
>> x = A\v
14.0664
-1.0664 Warning: Matrix is close to singular or badly
0.0000 scaled.
Results may be inaccurate. RCOND =
>> [v,e] = eig(A) 4.565062e-18
v=
x=
-0.2656 0.7444 -0.4082
-0.4912 0.1907 0.8165 1.0e+15 *
-0.8295 -0.6399 -0.4082
1.8014
-3.6029
e= 1.8014
>> diag(e) 2
1
ans = -1
1
Matrix Operations 3
5
There are also routines that let you find solutions
to equations. For example, if Ax=b and you want >> x1 = v'/B
to find x, a slow way to find x is to simply invert A
and perform a left multiply on both sides (more x1 =
on that later). It turns out that there are more
efficient and more stable methods to do this (L/U 4.0000 -3.0000 1.0000
decomposition with pivoting, for example).
Matlab has special commands that will do this for
you. >> x1*B
ans =
Before finding the approximations to linear
systems, it is important to remember that if A 1.0000 3.0000 5.0000
and B are both matrices, then AB is not
necessarily equal to BA. To distinguish the
difference between solving systems that have a Finally, sometimes you would like to clear all of
right or left multiply, Matlab uses two different your data and start over. You do this with the
operators, "/" and "\". Examples of their use are "clear" command. Be careful though, it does not
ask you for a second opinion and its results are
final.
>> v-b
>> clear
ans =
>> whos
-1
-2
-3
Matlab Tutorial
Multiplication of vectors and matrices must follow
Vector Functions strict rules. Actually, so must addition. In the
example above, the vectors are both column
vectors with three entries. You cannot add a row
Matlab makes it easy to create vectors and vector to a column vector. Multiplication, though,
matrices. The real power of Matlab is the ease in can be a bit trickier. The number of columns of
which you can manipulate your vectors and the thing on the left must be equal to the number
matrices. Here we assume that you know the of rows of the thing on the right of the
basics of defining and manipulating vectors and multiplication symbol:
matrices. In particular we assume that you know
how to create vectors and matrices and know
how to index into them. For more information on >> v*b
those topics see our tutorial on either vectors or ??? Error using ==> *
matrices. Inner matrix dimensions must agree.
>> v*b'
In this tutorial we will first demonstrate simple
manipulations such as addition, subtraction, and ans =
multiplication. Following this basic "element-wise"
operations are discussed. Once these operations 2 4 6
are shown, they are put together to demonstrate 4 8 12
how relatively complex operations can be defined 6 12 18
with little effort.
>> v'*b
First, we will look at simple addition and
subtraction of vectors. The notation is the same ans =
as found in most linear algebra texts. We will
define two vectors and add and subtract them: 28
>> v = [1 2 3]'
There are many times where we want to do an
v= operation to every entry in a vector or matrix.
Matlab will allow you to do this with "element-
1 wise" operations. For example, suppose you want
2 to multiply each entry in vector v with its
3 cooresponding entry in vector b. In other words,
suppose you want to find v(1)*b(1), v(2)*b(2),
>> b = [2 4 6]' and v(3)*b(3). It would be nice to use the "*"
symbol since you are doing some sort of
b= multiplication, but since it already has a
definition, we have to come up with something
2 else. The programmers who came up with Matlab
4 decided to use the symbols ".*" to do this. In fact,
6 you can put a period in front of any math symbol
to tell Matlab that you want the operation to take
>> v+b place on each entry of the vector.
>> plot(x,y)
Since we have opened the door to non-linear >> plot(x,y,'rx')
operations, why not go all the way? If you pass a >> help plot
vector to a predefined math function, it will return
a vector of the same size, and each entry is found PLOT Linear plot.
by performing the specified operation on the PLOT(X,Y) plots vector Y versus vector X. If X or
cooresponding entry of the original vector: Y is a matrix,
then the vector is plotted versus the rows or
>> sin(v) columns of the matrix,
whichever line up. If X is a scalar and Y is a
ans = vector, length(Y)
disconnected points are plotted.
0.8415
0.9093 PLOT(Y) plots the columns of Y versus their
0.1411 index.
If Y is complex, PLOT(Y) is equivalent to
>> log(v) PLOT(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is
ans = ignored.
j=
>> A = [ [1 2 3]' [3 2 1]' [2 1 3]']
2
A=
j= 1 3 2
2 2 1
3 3 1 3
>> B = A;
j= >> for j=2:3,
A(j,:) = A(j,:) - A(j-1,:)
4 end
>> A=
If you don't like the for loop, you can also use a
>> for j=2:3, while loop. The while loop repeats a sequence of
for i=j:3, commands as long as some condition is met. This
B(i,:) = B(i,:) - B(j-1,:)*B(i,j-1)/B(j-1,j-1) can make for a more efficient algorithm. In the
end previous example the number of time steps to
end make may be much larger than 20. In such a case
the for loop can use up a lot of memory just
B= creating the vector used for the index. A better
way of implementing the algorithm is to repeat
1 3 2 the same operations but only as long as the
0 -4 -3 number of steps taken is below some threshold.
3 1 3 In this example the D.E. y'=x-|y|, y(0)=1, is
approximated using Euler's Method:
B= >> h = 0.001;
>> x = [0:h:2];
1 3 2 >> y = 0*x;
0 -4 -3 >> y(1) = 1;
0 -8 -3 >> i = 1;
>> size(x)
B= ans =
1 3 2 1 2001
0 -4 -3
0 0 3 >> max(size(x))
ans =
2001
Another example where loops come in handy is
the approximation of differential equations. The >> while(i<max(size(x)))
following example approximates the D.E. y'=x^2- y(i+1) = y(i) + h*(x(i)-abs(y(i)));
y^2, y(0)=1, using Euler's Method. First, the step i = i + 1;
size, h, is defined. Once done, the grid points are end
found, and an approximation is found. The >> plot(x,y,'go')
approximation is simply a vector, y, in which the >> plot(x,y)
entry y(j) is the approximation at x(j).
>> h = 1/16;
>> x = 0:h:1;
>> y = 0*x;
>> size(y)
ans =
1 17
Let's start over. A new approximation is found by
>> max(size(y))
cutting the step size in half. But first, the picture
is completely cleared and reset using the clf
ans =
comand. (Note that I am using new vectors x1
and y1.)
17
for i=2:max(size(y)),
y(i) = y(i-1) + h*feval(func,x(i-1),y(i-1)); Matlab Tutorial
end
The If Statement
In this example, we will approximate the D.E.
y'=1/y. To do this you will have to create a file
called f.m with the following commands: In this tutorial we will assume that you know how
function [f] = f(x,y) to create vectors and matrices, know how to
% Evaluation of right hand side of a differential index into them, and know about loops. For more
% equation. information on those topics see one of our
tutorials on vectors, matrices, vector operations,
f = 1/y; loops, plotting, executable files, or subroutines.
With the subroutine defined, you can call it There are times when you want your code to
whenever necessary. Note that when you put make a decision. For example, if you are
comments on the 2nd line, it acts as a help file. approximating a differential equation, and the
Also note that the function f.m must be specified rate of change is discontinuous, you may want to
as a string, 'f'. change the rate depending on what time step you
>> help eulerApprox are on.
Here we will define an executable file that j = -1;
contains an if statement. The file is called by elseif (a>b)
Matlab, and it constructs a second derivative j = 2;
finite difference matrix with boundary conditions. end
There is a variable in the file called decision. If
this variable is less than 3, the file will find and The else statement provides a catch all that will
plot the eigen values of the matrix, if it is greater be executed if no other condition is met. The
than 3 the eigen values of the inverse of the following code sets the variable j to be 3.
matrix are found and plotted, otherwise, the
system is inverted to find an approximation to a = 4;
y'=sin(x) according to the specified boundary b = 4;
conditions. if (a<b)
j = -1;
elseif (a>b)
There are times when you want certain parts of j = 2;
your program to be executed only in limited else
circumstances. The way to do that is to put the j=3
code within an "if" statement. The most basic end
structure for an "if" statement is the following: This last example demonstrates one of the bad
habits that Matlab allows you to get away with.
if (condition statement) With finite precision arithmetic two variables are
(matlab commands) rarely exactly the same. When using C or
end FORTRAN you should never compare two floating
More complicated structures are also possible numbers to see if they are the same. Instead you
including combinations like the following: should check to see if they are close. Matlab
if (condition statement) does not use integer arithmetic so if you check to
(matlab commands) see if two numbers are the same it
elseif (condition statement) automatically checks to see if the variables are
(matlab commands) close. If you were to use C or FORTRAN then that
elseif (condition statement) last example could get you into big trouble. but
(matlab commands) Matlab does the checking for you in case the
. numbers are just really close.
.
. Matlab allows you to string together multiple
else boolean expressions using the standard logic
(matlab commands) operators, "&" (and), ¦ (or), and ˜ (not). For
end example to check to see if a is less than b and at
the same time b is greater than or equal to c you
The conditions are boolean statements and the would use the following commands:
standard comparisons can be made. Valid
comparisons include "<" (less than), ">" (greater if (a < b) & (b >= c)
than), "<=" (less than or equal), ">=" (greater Matlab commands
than or equal), "==" (equal - this is two equal end
signs with no spaces betweeen them), and "˜="
(not equal). For example, the following code will Example
set the variable j to be -1:
If you are not familiar with creating exectable
a = 2; files see our tutorial on the subject. Otherwise,
b = 3; copy the following script into a file called
if (a<b) ifDemo.m.
j = -1;
end decision = 3;
leftx = 0;
Additional statements can be added for more rightx = 1;
refined decision making. The following code sets
the variable j to be 2. lefty = 1;
righty = 1;
a = 4;
b = 3; N= 10;
if (a<b) h = (rightx-leftx)/(N-1);
x = [leftx:h:rightx]'; You can execute the instructions in the file by
simply typing ifDemo at the matlab prompt. Try
A = zeros(N); changing the value of the variable decision to see
what actions the script will take. Also, try
for i=2:N-1, changing the other variables and experiment.
A(i,i-1:i+1) = [1 -2 1];
end The basic form of the if-block is demonstrated in
the program above. You are not required to have
A = A/h^2; an elseif or else block, but you are required to
end the if-block with the endif statement.
A(1,1) = 1;
A(N,N) = 1; Matlab Tutorial
b = sin(x);
b(1) = lefty; Data Files
b(N) = righty;
Matlab does not allow you to save the commands
if(decision<3) that you have entered in a session, but it does
allow a number of different ways to save the
% Find and plot the eigen values data. In this tutorial we explore the different ways
[e,v] = eig(A); that you can save and read data into a Matlab
e = diag(e); session.
plot(real(e),imag(e),'rx');
title('Eigen Values of the matrix'); 1. Saving and
Recalling Data
elseif(decision>3)
2. Saving a
Session as Text
% Find and plot the eigen values of inv(A)
[e,v] = eig(inv(A)); 3. C Style
e = diag(e); Read/Write
plot(real(e),imag(e),'rx');
title('Eigen Values of the inverse of the Saving and Recalling Data
matrix');
As you work through a session you generate
else vectors and matrices. The next question is how
do you save your work? Here we focus on how to
save and recall data from a Matlab session. The
% Solve the system command to save all of the data in a session is
y = A\b; save. The command to bring the data set in a
linear = (lefty-righty+sin(leftx)-sin(rightx))/ data file back into a session is load.
(leftx-rightx);
constant = lefty + sin(leftx) - linear*leftx; We first look at the save command. In the
true = -sin(x) + linear*x + constant; example below we use the most basic form which
will save all of the data present in a session. Here
subplot(1,2,1); we save all of the data in a file called "stuff.mat."
plot(x,y,'go',x,true,'y'); (.mat is the default extension for Matlab data.)
title('True Solution and Approximation');
xlabel('x');
>> u = [1 3 -4];
ylabel('y');
>> v = [2 -1 7];
subplot(1,2,2);
>> whos
plot(x,abs(y-true),'cx');
Name Size Bytes Class
title('Error');
xlabel('x');
u 1x3 24 double
ylabel('|Error|');
array
v 1x3 24 double
array
end
Grand total is 6 elements using 48 bytes
fp = fopen('laser.dat','r');
fseek(fp,pos,'bof');
tmp = fread(fp,2,'double');
pos = ftell(fp);
fclose(fp);