PDF Matlabprashant
PDF Matlabprashant
PDF Matlabprashant
This is a tutorial to help you get started in Matlab. Examples of Matlab code
in this pamphlet are in typewriter font like this. As you read through the
text,
type and execute in Matlab all of the examples, either at the » command line
prompt or in a test program you make called test.m. Longer sections of code are
set off and named. This code can be found as files on the Physics 330 web page
at physics.byu.edu/Courses/Computational.
This booklet can also be used as a reference manual because it is short, it has
lots of examples, and it has a table of contents and an index. It is almost true
that the basics of Matlab are in chapters 1-7 while physics applications are in
chapters 8-14. Please tell us about mistakes and make suggestions to improve the
text (michael_ware@byu.edu).
To find more details see the very helpful book Mastering MATLAB 7 by
Duane Hanselman and Bruce Littlefield.
Contents
1 Running Matlab 1
1.1 Basic Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Matrix Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Calculating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Matlab Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2 Scripts 9
2.1 The Matlab Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Script Files.......................................................................................................10
2.3 Input and Output...........................................................................................11
2.4 Input.................................................................................................................11
2.5 Output..............................................................................................................12
2.6 File IO...............................................................................................................12
3 Debugging Code 15
3.1 Make Your Code Readable.............................................................................15
3.2 Debugging.......................................................................................................16
3.3 Pause command.............................................................................................18
5 Line Plots 25
5.1 Linear Plots......................................................................................................25
5.2 Plot Appearance...............................................................................................27
5.3 Multiple Plots..................................................................................................28
Vii
6 Make Your Own Functions: Inline and M-files 39
7.1 Inline Functions ..........................................................................................................................39
7.2 M-file Functions 39
7.3 Functions With Multiple Outputs..............................................................................................................41
Get on a department PC or buy Student Matlab for your own machine and
start the program. Locate the command window in Matlab, usually at the
lower
left. Type the commands that appear on their own line in typewriter font into
Type your commands here
the command window at the » prompt as we go along and then hit Enter to
see how they work.
help besselj
t The help command will
Briefly look over the help material. At the bottom of the help material, there only work at the command
is a blue “doc besselj” link. Click on this link to open Matlab’s help prompt if you know exactly
browser. You can also open this browser by selecting the “Product Help” how Matlab spells the topic
option in the Help menu. You can browse and search these extensive help you are looking for. For
resources to get further information about all the material we present in this more general searches, use
lookfor at the command
book.
prompt or the search func-
tionality in the help menu.
It’s a Calculator
You can use Matlab as a calculator by typing commands at the » prompt,
like these. Try them out.
1+1
2*3
5/6
exp(-3)
atan2(-1,2)
And just like many hand calculators, ans in Matlab means the last result
calcu- lated.
sin(5)
ans
Note that Matlab’s trig functions are permanently set to radians mode.
Note also that the way to enter numbers like 1.23 × 1015 is
1
2 Chapter 1 Running Matlab
1.23e15
And here’s another useful thing. The up-arrow key ↑ will display
previous commands. And when you back up to a previous command that you
like, hit Enter and it will execute. Or you can edit it when you get to it (use ←,
→, and Del),
then execute it. Try doing this now to re-execute the commands you have already
typed.
1.2 Variables
Symbolic packages like Mathematica and Maple have over 100 different data
types; Matlab has just three: the matrix, the string, and the cell array. You’ll
use matrices extensively, strings once in a while, and you probably won’t have
need for cell arrays very often.
Variables are not declared before they are used, but are defined on the fly.
The assignment command in Matlab is simply the equal sign. For instance,
a=20
creates the variable a and assigns the value 20 to it. Note that variable names in
t An assign statement in Matlab are case sensitive, so watch your capitalization. If you want to see the
pro- gramming is not the value of a variable, just type its name like this
same as an equation in
math. For instance, it a
makes perfect sense to
write a=a+1 as as- sign Numerical Accuracy
statement: it tells the
computer to evaluate the All numbers in Matlab have 15 digits of accuracy. When you display numbers to
thing on the right of the = the screen, like this
(get the value of a and
add 1 to it) and then store 355/113
the evaluated quantity in
the variable on the left of
you may think Matlab only works to 5 significant figures. This is not true; it’s
the = (in this case it puts just displaying five. If you want to see them all type
the eval- uated quantity
format long e
back into the memory slot
labeled The e stands for exponential notation. The four most useful formats to set are
by a). On the other hand,
the mathematical equation format short % the default format
format long
a = a + 1 is clearly format long e
format short e
ridiculous.
Matlab knows the number π.
pi
Try displaying π under the control of each of the three formats given above.
String Variables
String variables contain a sequence of characters, like this
s= This is a string
' '
If you need an apostrophe in your string, repeat a single quote, like this:
t= Don
' ''t worry '
And if you just want to access part of a string, like the first 7 characters of s
(defined above) use
s(1:7)
clear pi
will erase your user-defined value and restore the default value. If you want
to erase all variables in the workspace, simply type
clear
The array
a=[1,2,3,4]
size(a)
is a 1×4 matrix (row vectors are built with commas); the array
b=[1;2;3;4]
size(b)
4 Chapter 1 Running Matlab
And if you leave the middle number out of this colon construction, like this
t=0:20
The variable c now contains the first two elements of the second row of A.
To load a column vector b with all of the entries of the third column of the
matrix A, you can use the syntax
b=A(1:end,3)
Recall that the first index of a matrix is the row index, so this command tells
Matlab to select all of the rows of A in column 3. Since this type of operation is
so common in Matlab, there is a shorthand for selecting all of the entries in a
given dimension: just leave off the numbers around the colon, like this
b=A(:,3)
And to load a row vector c with the contents of the second row of the matrix A use
c=A(2,:)
1.4 Calculating 5
1.4 Calculating
Matlab only crunches numbers. It doesn’t do symbolic operations, so in that
sense it is much less capable than Mathematica or Maple. But because it t Testimonial: “I, Scott
doesn’t have to do hard symbolic stuff, it can handle numbers much faster Berge- son, do hereby
than Mathematica or Maple can. Here’s a brief summary of what it can do certify that I wrote a data
with numbers. analysis code in Maple that
took 25 min- utes to run.
When I con- verted the
Add and Subtract code to Matlab it took 15
seconds.”
Matlab knows how to add and subtract numbers, arrays, and matrices. As long as
A and B are two variables of the same size (e.g., both 2×3 matrices), then A+B
and
A-B will add and subtract them as matrices:
A=[1,2,3;4,5,6;7,8,9]
B=[3,2,1;6,4,5;8,7,9]
A+B
A-B
Multiplication
The usual multiplication sign * has special meaning in Matlab. Because
every- thing in Matlab is a matrix, * means matrix multiply. So if A is a 3×3
matrix and B
is another 3×3 matrix, then A*B will be their 3×3 product. Similarly, if A is a
3×3
matrix and C is a 3×1 matrix (column vector) then A*C will be a new 3×1
column vector. And if you want to raise A to a power by multiplying it by itself n
times, you
just use
A^n
For a language that thinks everything in the world is a matrix, this is perfectly
natural. Try
A*B
A*[1;2;3]
A^3
./
6 Chapter 1 Running Matlab
This “dot" form of the division operator divides each element of an array by
the corresponding element in another (equally sized) array. If we want to
raise each element of an array to a power, we use
.^
[1,2,3].*[3,2,1]
[1,2,3]./[3,2,1]
[1,2,3].^2
These “dot” operators are very useful in plotting functions and other kinds of
signal processing.
Note that in this case the things we are dividing are scalars (or 1×1 matrices
in Matlab’s mind), so Matlab will just treat this like the normal division of
two
numbers (i.e. we don’t have to use the ./ command, although it wouldn’t hurt
if we did).
n=1:10000;
sum(1./n.^2)
You can compare this answer with the sum to infinity, which is π2/6, by typing
ans-pi^2/6
For matrices the sum command produces a row vector which is made up
of the sum of the columns of the matrix.
A=[1,2,3;4,5,6;7,8,9]
sum(A)
If you want to add up all of the elements in the array, just nest the sum
command like this
sum(sum(A))
1.5 Matlab Functions 7
Complex Arithmetic
Matlab works as easily with comple x numbers as with real ones. The variable i
¸
is the usual imaginary number1 i −1, unless you are so foolish as to assign it
=
some other value, like this:
i=3
If you do this you no longer have access to imaginary numbers, so don’t ever do it. If ¼ Don’t ever use i as a
you accidentally do it the command clear i will restore it to its imaginary vari- able name.
luster.
By using i you can do complex arithmetic, like this
z1=1+2i
z2=2-3i cos(x)
sin(x)
z1+z2 tan(x)
z1-z2 acos(x)
z1*z2 asin(x)
z1/z2
atan(x)
atan2(y,x)
And like everything else in Matlab, complex numbers work as elements of arrays
exp(x)
and matrices as well. log(x)
When working with complex numbers we quite often want to pick off the real log10(x)
part or the imaginary part of the number, find its complex conjugate, or find log2(x)
sqrt(x)
its magnitude. Or perhaps we need to know the angle between the real axis cosh(x)
and the complex number in the complex plane. Matlab knows how do all of sinh(x)
these tanh(x)
acosh(x)
z=3+4i asinh(x)
real(z) atanh(x)
imag(z) sign(x)
conj(z) airy(n,x)
abs(z) besselh(n,x)
angle(z) besseli(n,x)
besselj(n,x)
Perhaps you recall Euler’s famous formula ei x
= cos x +i sin x? Matlab besselk(n,x)
knows it too.
bessely(n,x)
erf(x)
exp(i*pi/4)
erfc(x)
Matlab knows how to handle complex arguments for all of the trig, erfcx(x)
erfinv(x)
exponential, and hyperbolic functions. It can do Bessel functions of complex gamma(x)
arguments too. expint(x)
legendre(n,x)
factorial(x)
1.5 Matlab Functions Table 1.1 A sampling of the math-
ematical functions available in
Matlab knows all of the standard functions found on scientific calculators and Matlab.
even many of the special functions like Bessel functions. Table 1.1 shows a
bunch of them. All of the functions in Table 1.1 work like the “dot” operators
discussed
1
If you are in a discipline where j is used for the imaginary number, Matlab can be your friend
too. The variables i and j have the same meaning in Matlab, and everything we say about i
works the same with j.
8 Chapter 1 Running Matlab
in the previous section (e.g. .* and ./). This means, for example, that it
makes sense to take the sine of an array: the answer is just an array of sine
values. For example, type
sin([pi/4,pi/2,pi])
Typing in commands in the command window is just the tip of the iceberg of
what Matlab can do for you. Most of the work you will do in Matlab will be
stored in files called scripts, or m-files, containing sequences of Matlab
commands to be executed over and over again.
• The Editor window at the upper left is where you write sequences of
Matlab commands called scripts and then save them to be executed all
together. This is where we’ll spend most of our time when using Matlab.
• The Workspace window at the upper right displays all of the variables
that Matlab currently has in memory. Double clicking on the yellow name
icon of a variable launches the Array Editor, which allows you to view and
modify the values in your variables. It’ll come in very handy when we’re
debugging scripts.
9
10 Chapter 2 Scripts
The desktop windows can be rearranged using drag, drop, and docking. More
options for rearranging are in the Desktop menu, but wait until you’ve used
Matlab a while before you start dragging things around.
Running a Script
Before you can execute a script, you need to point Matlab’s current folder to
the place where your script is saved. Matlab displays the current folder in a
text box on the toolbar. You can change the directory by typing in the box or
clicking the button next to the current directory box (i.e. the button with the
three dots in it). Once your directory is set to the right place, you execute a
script by typing the name of your file without the .m extension in the
command window, like this:
test
The clear command clears all variables from Matlab’s memory and makes sure
that you don’t have leftover junk active in Matlab that will interfere with your
code. The close all command closes any figure windows that are open.
The obvious exception to the rule of beginning your scripts with these commands
is if you need to keep some data in memory for your script to run, or if you
need to leave a plot window open. Add these two lines at the beginning of
your test.m script, and run it again.
and then execute it. Look at the output in the command window. Even though
the variable a didn’t print, it is loaded with sin(5), as you can see by typing
a
2.4 Input
To have a script request and assign a value to the variable N from the
keyboard, put the command
N=input(' Enter a value for N - )
'
in your script. If you enter a single number, like 2.7, then N will be a scalar
variable. If you enter an array, like this: [1,2,3,4,5], then N will be an array. If
you enter a matrix, like this: [1,2,3;4,5,6;7,8,9], then N will be a 3x3 matrix. And
if you don’t want the variable you have entered to echo on the screen, end the
input command line with a semicolon.
12 Chapter 2 Scripts
2.5 Output
To display printed results you can use the fprintf command. Type the
following examples in the command window to see what each one produces.
fprintf( ' N =%g \n ,500)
'
Note that the stuff inside the single quotes is a string which will print on the
screen; % is where the number you are printing goes; and the stuff
immediately after % is a format code. A g means use the “best” format; if the
number is really big or really small, use scientific notation, otherwise just throw
6 significant figures on the screen in a format that looks good. The format
6.2f means use 2 decimal places and fixed-point display with 6 spaces for the
number. An e means scientific notation, with the number of decimal places
controlled like this: 1.10e.) Note: \n is the command for a new line. If you
want all the details on this stuff, see the Matlab help entry for fprintf.
2.6 File IO
Reading from a file
You can also enter data from a file filled with rows and columns of numbers.
Matlab reads the file as if it were a matrix with the first line of the file going
into the first row of the matrix. If the file were called data.fil and looked
like this:
1 2 3
4 5 6
7 8 9
load data.fil
would produce a matrix called data filled with the contents of the file.
Writing to a file
The fprintf command will also write output to a file. The code in Listing
2.1 writes a file filled with a table of values of x and exp(x) from 0 to 1. Note that
when using Windows that the end of line indicator is \r\n rather than \n.
2.6 File IO 13
After you try this, open file1.txt, look at the way the numbers appear in it, and
compare them to the format commands %6.2f and %12.8f to learn what
they mean. Write the file again using the %g format for both columns and
look in the file again.
Chapter 4
Loops and Logic
To solve many physics problems you have to know how to write loops and
how to use logic.
4.1 Loops
A loop is a way of repeatedly executing a section of code. It is so important
to know how to write them that several common examples of how they are used
will be given here. The two kinds of loops we will use are the for loop and the
while loop. We will look at for loops first, then study while loops a bit
later in the logic section.
The for loop looks like this:
for n=1:N
% Put code here
end
which tells Matlab to start n at 1, then increment it by 1 over and over until it
counts up to N, executing the code between for and end for each new value of n.
Here are a few examples of how the for loop can be used.
Create a breakpoint at the x=0 line in the code, run then code, and then
step through the first several iterations of the for loop using F10. Look at the
values of
19
20 Chapter 4 Loops and Logic
n and s in the Workspace window and see how they change as the loop
iterates. Once you are confident you know how the loop works, press F5 to let
the script finish executing.
We can calculate the same sum using matrix operators like this
n=1:N;
sum(1./n.^2)
This matrix operator method is usually much faster. Try both the loop way
and this sum command way and see which is faster. To slow things down enough
that you can see the difference change 10,000 to 100,000. When we tested
this, the colon (:) and sum way was 21 times faster than the loop, so use
array operators whenever you can. You should use the colon command
whenever possible because it is a pre-compiled Matlab command. To do
timing checks use the tic and toc commands. Look them up in online help.
To get some more practice with loops, let’s do the running sum
m
X
m n 1n (4.2)
S =2
n=1 n
a where a =
for values of m from 1 to a large number N .
Listing 4.2 (ch4ex2.m)
N=100;
a = zeros(1,N);
% Fill the a array
for n=1:N
a(n) = 1 / n^2;
end
S = zeros(1,N);
% Do the running sum
for m=1:N
S(m) = sum( a(1:m) );
end
m=1:N
plot(m,S)
Notice that in this example we pre-allocate the arrays a and S with the zeros
command before each loop. If you don’t do this, Matlab has to go grab an
extra little chunk of memory to expand the arrays each time the loop iterates
and this makes the loops run very slowly as N gets big.
We also could have done this cumulative sum using colon operators and the
cumsum command, like this:
4.1 Loops 21
n=1:100;
S=cumsum(1./n.^2);
for n=2:N % start the loop at n=2 because we already loaded n=1
P=P*n; % multiply by n each time, put the answer back into P
end % end of the loop
Now use Matlab’s factorial command to check that you found the right answer:
factorial(20)
You should be aware that the factorial command is a bit limited in that it
won’t act on an array of numbers in the way that cos, sin, exp etc. do. A better
factorial command to use is the gamma function Γ(x) which extends the factorial
function
to all complex values. It is related to the factorial function by Γ(N + 1) = N !,
and is called in Matlab using the command gamma(x), so you could also check
the
answer to your factorial loop this way:
gamma(21)
a1 = 1 ; an 2n − 1
1 = an. (4.4)
+
2n + 1
To use these coefficients we need to load them into an array a so that a(1) =
a1, a(2) = a2, · · · . Here’s how we could do this using a for loop to load a(1)...a(20):
22 Chapter 4 Loops and Logic
Note that the recursion relation was translated into Matlab code just as it appeared
in the formula: a(n+1)=(2*n-1)/(2*n+1)*a(n). The counting in the loop was
then adjusted to fit by starting at n = 1, which loaded a(1 + 1) = a(2), then a(3),
etc., then ended at n = 19, which loads a(19 + 1) = a(20). Always make your
code fit the mathematics as closely as possible, then adjust the other code to fit.
This
will make your code easier to read and you will make fewer mistakes.
4.2 Logic
Often we only want to do something when some condition is satisfied, so we
need logic commands. The simplest logic command is the if command, which
works like this:
Listing 4.5 (ch4ex5.m)
clear; close all;
a=1;
b=3;
if a>0
c=1 % If a is positive set c to 1
Equal == else
Less than < c=0 %if a is 0 or negative, set c to zero
end
Greater than >
Less than or equal <= % if either a or b is non-negative, add them to obtain c;
Greater than or equal >= % otherwise multiply a and b to obtain c
Not equal if a>=0 | b>=0 % either non-negative
c=a+b
else
∼= c=a*b % otherwise multiply them to obtain c
And & end
Or |
Not ∼
Table 4.1 Matlab’s logic elements
Study each of the commands in the code above and make sure you
understand what they do. You can build any logical condition you want if you
just know the basic logic elements listed in Table 4.1.
4.2 Logic 23
while Loops
There is also a useful logic command that controls loops: while. Suppose you
don’t know how many times you are going to have to loop to get a job done,
but instead want to quit looping when some condition is met. For instance,
suppose you want to add the reciprocals of squared integers until the term you
.
just added is less than 1e-10. Then you would change the loop in the 1/n2
example to look like this
Listing 4.6 (ch4ex6.m)
clear; close all;
n=1;
while term > 1e-10 % loop until term drops below 1e-10
n=n+1; % add 1 to n so that it will count: 2,3,4,5,...
term=1/n^2; % calculate the next term to add
s=s+term; % add 1/n^2 to s until the condition is met
end % end of the loop
This loop will continue to execute until term<1e-10. Note that unlike the for
loop, here you have to do your own counting, being careful about what value
n
starts at and when it is incremented (n=n+1). It is also important to make
sure that the variable you are testing (term in this case) is loaded before the loop
starts with a value that allows the test to take place and for the loop to run
(term must pass the while test.)
Sometimes while loops are awkward to use because you can get stuck in
an infinite loop if your check condition is never false. The break command ¼ If you get stuck in an infi-
nite loop, press Ctrl-C in
is designed to help you here. When break is executed in a loop the script
the Command Window to
jumps to just after the end at the bottom of the loop. The break command also
manually stop the
works with for loops. Here is our sum loop rewritten with break
program and return
Listing 4.7 (ch4ex7.m) control back to you.
clear; close all;
break
end
end % end of the loop
fprintf(
' Sum = %g \n ,s)
'
4.2 Logic 23
Chapter 7
Make Your Own Functions: Inline and M-files
You will often need to build your own Matlab functions as you use Matlab to
solve problems. You can do this either by putting simple expressions into
your code by using Matlab’s inline command, or by defining function files
with .m extensions called M-files.
clear;close all;
f=inline( sin(x.*y)./(x.^2+y.^2) , x , y );
' ' ' ' ' '
x=-8:.1:8;
y=x;
plot(x,f(x,2))
[X,Y]=ndgrid(x,y);
figure
surf(X,Y,f(X,Y))
The expression that defines the function is in the first string argument to
inline and the other string entries tell inline which argument goes in which
input slot when you use the function.
39
40 Chapter 7 Make Your Own Functions: Inline and M-files
f=sin(x.*y)./(x.^2+y.^2);
function output=name(input)
The word function is required, output is the thing the function passes back
to whomever called it, name should match the filename of the script (e.g.
“trig.m” above), and input is the argument list of the function. When the
function is called, the arguments passed in must match in number and type
defined in the definition. The function m-file needs to assign the output an
appropriate value.
To call the function, you to write a separate script like this
Listing 7.3 (calling.m)
clear;close all;
h=0.1;
x=-8:h:8;
y=x;
plot(x,trig(x,2))
[X,Y]=ndgrid(x,y);
figure
surf(X,Y,trig(X,Y))
The names of the variables in input and output of a function are local to
the function, so you don’t have to worry about overwriting variables in the file
that called the function. However, this also means that the variables inside
Matlab functions are invisible in the command window or the calling m-file. For
example, you cannot reference the variable f in the calling.m script, nor can you
access the variable h in the trig.m script.
If you want variables used outside the function to be visible inside the
function and vice-versa, use Matlab’s global command. This command
declares certain variables to be visible in all Matlab routines in which the global
command appears.
For instance, if you put the command
global a b c;
both in a script that calls trig.m and in trig.m itself, then if you give a, b,
and c values in the main script, they will also have these values inside
trig.m. This construction will be especially useful when we use Matlab’s
differential equation solving routines in Chapter 13.
7.3 Functions With Multiple Outputs 41
Note that when a function returns more than one output variable, the names
of these results are put in square brackets, as in SquareWell.m. When you
call the function, you use the same type of format to receive the output, as in
this example
Listing 7.5 (ch7ex5.m)
clear; close all;
title(s);
xlabel( x (nm) );
' '
ylabel( \Psi(x) );
' '
Note that we didn’t have to call the variables the same names when we used them
outside the function in the main script (e.g. we used Energy instead of E).
This is because all variables inside functions are local to these programs and
Matlab doesn’t even know about them in the command window. Confirm this
by trying to display the value of E and hbar in the command window.
E
hbar
Chapter 8
Linear Algebra and Polynomials
Almost anything you learned about in your linear algebra class Matlab has a
command to do. Here is a brief summary of the most useful ones for physics.
Matlab will solve the matrix equation Ax = b, where A is a square matrix, where
b is a known column vector, and where x is an unknown column vector. For
instance, the system of equations
x+ z = 4
−x + y + z = 4 (8.1)
x− y+ z = 2,
Then using the backslash symbol \ (sort of “backwards divide”) Matlab will use
Gaussian elimination to solve this system of equations, like this:
x=A\b
43
44 Chapter 8 Linear Algebra and Polynomials
(notice that there isn’t a period). If your matrices are real, then there is no
differ- ence between these two commands and you might as well just use A . '
Notice that if a is a row vector then a is a column vector. You will use the
'
transpose operator to switch between row and column vectors a lot in Matlab,
like this
[1,2,3]
[1,2,3] '
[4;5;6]
[4;5;6] '
Flipping Matrices
Sometimes you want to flip a matrix along the horizontal or vertical
directions. The command to do this are
fliplr(A) % flip A, left column becomes right, etc.
and
flipud(A) % flip A, top row becomes bottom, etc.
Determinant
Find the determinant of a square matrix this way
det(A)
To build a matrix V whose columns are the eigenvectors of the matrix A and
another matrix D whose diagonal elements are the eigenvalues corresponding
to the eigenvectors in V use
[V,D]=eig(A)
To select the 3rd eigenvector and load it into a column vector use
v3=V(:,3) % i.e., select all of the rows (:) in column 3
8.3 Vector Operations 45
Fancy Stuff
Matlab also knows how to do singular value decomposition, QR factorization,
LU factorization, and conversion to reduced row-echelon form. And the
commands rcond and cond will give you the condition number of a matrix.
To learn about these ideas, consult a textbook on linear algebra. To learn how
they are used in Matlab use the commands;
help svd
help QR
help LU
help rref
help rcond
help cond
Special Matrices
Matlab will let you load several special matrices. A few of the more useful
ones are the identity matrix
I=eye(4,4) % load I with the 4x4 identity matrix. The
% programmer who invented this syntax must
% have been drunk
a=[1,2,3];
b=[3,2,1];
dot(a,b)
cross(a,b)
Cross products only work for three-dimensional vectors, but dot products can be
used with vectors of any length. Note that the dot function is not the same
thing as the “dot times” operator (.*). Type
dot(a,b)
a.*b
and compare the output. Explain the difference to someone sitting nearby.
8.4 Polynomials
Polynomials are used so commonly in computation that Matlab has special com-
mands to deal with them. The polynomial x4 +2x3 −13x2 −14x+24 is
represented in Matlab by the array [1,2,-13,-14,24], i.e., by the coefficients of
the polyno-
mial starting with the highest power and ending with the constant term. If any
power is missing from the polynomial its coefficient must appear in the array as a
zero. Here are some of the things Matlab can do with polynomials.
Roots of a Polynomial
The following command will find the roots of a polynomial:
p=[1,2,-13,-14,24];
r=roots(p)
Multiply Polynomials
The command conv returns the coefficient array of the product of two polynomi-
als.
a=[1,0,1];
b=[1,0,-1];
c=conv(a,b)
Divide Polynomials
Remember synthetic division? Matlab can do it with the command deconv, giving
you the quotient and the remainder.
a=[1,1,1]; % a=x^2+x+1
b=[1,1]; % b=x+1
After you do this Matlab will give you q=[1,0] and r=[0,0,1]. This means that
q = x + 0 = x and r = 0x2 + 0x + 1 = 1, so
x2 + x + 1 1
Evaluate a Polynomial
If you have an array of x-values and you want to evaluate a polynomial at each
one, do this:
% define the polynomial
a=[1,2,-13,-14,24];
% plot it
plot(x,y)
Chapter 9
Fitting Functions to Data
x=linspace(0,pi,50);
If you want to fit data to a more general function than a polynomial, you need to
work a little harder. Suppose we have a set of data points (xj , y j ) and a proposed
fitting function of the form y = f (x, a1, a2, a3, ...). For example, we could try to
fit
49
50 Chapter 9 Fitting Functions to Data
s=sum((y-funcfit(a,x)).^2);
With these two functions built and sitting in your Matlab directory we are
ready to do the fit.
Matlab has a nice multidimensional minimizer routine called fminsearch
that will do fits to a general function if you give it a half-decent initial guess for
the fitting parameters. The basic idea is that you pass a reference to your
leastsq.m function to fminsearch, and it varies the free parameters in the
variable a in a systematic way to find the values that minimizes the error
function S (calculated by leastsq.m from the (x, y ) data and the an’s).
Note, however, that fminsearch is a minimizer, not a zero finder. So it
may find a local minimum of the error function which is not a good fit. If it
fails in this way you need to make another initial guess so fminsearch can take
another crack at the problem.
Here is a piece of code that performs the fitting functions. First, it loads
the data from a file. For this to work, the data needs to be sitting in the file
data.fil as two columns of (x, y ) pairs, like this
0.0 1.10
0.2 1.20
0.4 1.52
0.6 1.84
0.8 2.20
1.0 2.70
Then the program asks you to enter an initial guess for the fitting parameters, plot
the initial guess against the data, then tell fminsearch to do the least squares fit.
The behavior of fminsearch can be controlled by setting options with
Matlab’s optimset command. In the code below this command is used to set
the Matlab variable TolX, which tells fminsearch to keep refining the
parameter search until the parameters are determined to a relative accuracy of
TolX. Finally, it plots the best fit against the data. We suggest you save it for
future use.
Listing 9.4 (datafit.m)
clear;close
% Uses fminsearch to least squares fit a function defined
% in funcfit.m to data read in from data.fil
xplot=xmin:dx:xmax;
plot(x,y, b* ,xplot,yplot, r- )
' ' ' '
end
% Do the fit with the option TolX set; fminsearch will adjust
% a until each of its elements is determined to within TolX.
% If you think fminsearch could do better, reduce
TolX. option=optimset( TolX ,1e-5); ' '
xlabel( x )
' '
It’s a little more work to make three files to get this job done, but we
suggest you learn how to use fminsearch this way. Function fitting comes up
all the time. Once you get the hang of it, you can choose to fit to any function
you like just by changing the definition in funcfit.m. The other two scripts
usually don’t need to be modified