Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PDF Matlabprashant

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 46

INTRODUCTION TO MATLAB

Ross L. Spencer and Michael Ware

Department of Physics and Astronomy


INTRODUCTION TO MATLAB

Ross L. Spencer and Michael Ware

Department of Physics and Astronomy

Brigham Young University

© 2004-2011 Ross L. Spencer, Michael Ware, and Brigham Young University

Last Revised: January 25, 2013


Preface

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

Table of Contents vii

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

4 Loops and Logic 19


4.1 Loops................................................................................................................19
4.2 Logic.................................................................................................................22

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

7 Linear Algebra and Polynomials 43


8.1 Solve a Linear System ...........................................................................................................................43
8.2 Matrix Operations ...........................................................................................................................43
8.3 Vector Operations ..........................................................................................................................45
8.4 Polynomials ...........................................................................................................................46

8 Fitting Functions to Data 49


9.1 Fitting Data to a Polynomial.......................................................................................................................49
9.2 General Fits with fminsearch....................................................................................................... 49

9 Solving Nonlinear Equations 53


10.1 Solving Transcendental Equations............................................................................................................53
10.2 Systems of Nonlinear Equations................................................................................................................55

10 Derivatives and Integrals 63


12.1 Derivatives 63
12.2 Integrals 66
12.3 Matlab Integrators 68
Chapter 1
Running Matlab

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.

1.1 Basic Functionality Figure 1.1 The command


window allows you to directly
Getting Help issue com- mands to Matlab.
This manual is a guided tour of some of the useful features of Matlab, but we
can’t
cover everything. You can get help by typing the commands help or lookfor at
the » prompt. For example perhaps you are wondering about the Matlab’s Bessel
function routines. Type

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.

¼ Matlab will let you set pi


to anything you want, like
this, pi=2; but please
don’t.
1.3 Matrix Variables 3

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)

Some Matlab commands require options to be passed to them using


strings. Make sure you enclose them in single quotes, as shown above. If you
want to know more about how to handle strings type help strings.

Clearing the Workspace


Matlab keeps all the variables you declare in memory until you tell it to erase
them. In Matlab lingo, the place where user-defined variables are stored is
referred to as the workspace. To erase a single variable from the workspace, type
clear and then the variable name. For instance, if you accidentally set pi to
something other than π, the command

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

and all your variables will be gone.

1.3 Matrix Variables


Matlab thinks the number 2 is a 1×1 matrix:
N=2
size(N)

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

is a 4×1 matrix (column vectors are built with semicolons).


The matrix
A=[1,2,3;4,5,6;7,8,9]
size(A)

is a 3×3 matrix (row entries separated by commas, different rows separated


by semicolons.) It should come as no surprise that the “Mat” in Matlab stands
for
matrix.
When you want to access the elements of a matrix you use the syntax A(row,column).
For example, to get the element of A in the 3rd row, 5th column you would
use A(3,5). And if you have a matrix or an array and you want to access the
last element in a row or column, you can use Matlab’s end command, like
this:
c(end)
A(3,end)

The Colon (:) Command


¼ Pay attention to this You can build large, evenly spaced arrays using the colon (:) command. To build
section.
an array x of x-values starting at x = 0, ending at x = 10, and having a step size
Understanding the colon
of
command clearly will make
your life much easier. dx = 0.5 type this:
x=0:.5:10

And if you leave the middle number out of this colon construction, like this
t=0:20

then Matlab assumes a step size of 1.

Selecting Rows and Columns


Sometimes you will want to select part of a matrix and load it into another
array. This is also done with Matlab’s all-purpose colon (:) command. To select
just part of row or column, use commands like this:
c=A(2,1:2)

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

But there are lots of times when we don’t want to do matrix


multiplication. Sometimes we want to take two big arrays of numbers and
multiply their corre- sponding elements together, producing another big array
of numbers. Because we do this so often (you will see many examples later ¼ This “dot” operator stuff
on) Matlab has a special symbol for this kind of multiplication: is important. Be patient if
it is a little confusing
.* now.
When we start plotting
For instance, the dot multiplication between the arrays [a,b,c] and [d,e,f]
and doing real calculations
would be the array [a*d,b*e,c*f]. And since we might also want to divide two
this will all become clear.
big arrays this way, Matlab also allows the operation

./
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
.^

For example, try

[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.

Arithmetic with Array Elements


If you just want to do some arithmetic with specific values stored in your
arrays, you can just access the individual elements. For instance, if you want
to divide the third element of A by the second element of B, you would just
use
A(3)/B(2)

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).

Sum the Elements


The command sum adds up the elements of the array. For instance, the following
commands calculate the sum of the squares of the reciprocals of the integers from
1 to 10,000.

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])

and see what you get.


Also, note that the natural log function ln x is the Matlab function log(x). To
get the base-10 log, use log10.
clc clears the com-
mand window;
Housekeeping Functions
use- ful for
beautifying printed Matlab also has a bunch of other functions that don’t really do math but are
output
useful in programming. We’ve listed several of them in Table 1.2. Take a
clear clears all assigned minute to familiarize yourself with the functions in the table; many of them
variables will come in handy. Try

close all closes all figure floor([1.5,2.7,-1.5])


windows;
to convince yourself that these functions operate on matrices and not just
close 3 Close figure window on single numbers.
3

length(a) the number of Max and Min


elements in a vector
Two of the more useful housekeeping commands are max and min, which
size(c) the dimensions of return the maximum and minimum values of an array. And with a slight change
a matrix of syntax they will also return the indices in the array at which the maximum and
minimum occur. For example, create a couple of arrays like this
ceil(x) the nearest integer
greater than x x=0:.01:5;
y=x.*exp(-x.^2);
fix(x) the nearest integer
to x looking toward and then you can find the max and min like this
zero
ymin=min(y)
floor(x) the nearest integer ymax=max(y)
less than x
You can also find the max and min along with the array indices imax and
round(x) the nearest integer imin where they occur, like this
to x
[ymin,imin]=min(y)
sign(x) the sign of x and [ymax,imax]=max(y)
returns 0 if x=0
Look at the values of imin and imax and discuss them with your lab partner until
Table 1.2 A sampling of “house- you understand what they mean.
keeping” functions
Chapter 2
Scripts

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.

2.1 The Matlab Desktop


The default layout of the windows in the Matlab desktop often looks something
like this:

The different windows provide the following functionality.

• 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 Command window allows you issue commands directly to 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 Command History window shows a history of all of the commands


you have typed in the command window. You can re-execute a
command by double-clicking it in this window.

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.

2.2 Script Files


To make a script, create a new text file in Matlab by clicking on the empty
doc- ument on the tool bar. Then save this file with a .m extensions
(automatically added in Windows) in the directory where you want to store
t Make a folder where you your Matlab scripts. After you’ve created a script, you fill it with a sequence
can store all of the scripts of Matlab commands that will be executed from top to bottom just as if you
for this class. Work out an had typed them on the command screen. Create a script file now, put the sample
arrangement to share
command x=sin(2) in it, and save it as test.m in a directory where you can
these files with your lab
partner.
find it again.
Script file names cannot start with numbers, like 430lab1a.m. You execute
scripts by typing their name, and when Matlab receives the start of a number
in a command it thinks a calculation is coming. Since something like
430lab1a is not a valid calculation, Matlab will give you an error if you try
and name your scripts like this. Also, do not use a space or a period in the file
¼ Script names cannot begin name. If you want to separate words in your file name, you can use the
with numbers or contain underscore character (e.g. my_script.m).
spaces or periods

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

Remember to save changes to your script before executing it (Ctrl-s is a quick


way) or Matlab in the command window won’t know that you have made
changes to the script. Use this method to run the test.m script you wrote in
the previous section.
A convenient alternative for running a script is to use the “Save and Run”
shortcut key, F5, while in the m-file editor window. This shortcut will save
your script file, ask you if you want to switch the current directory to where your
script file is saved (if it isn’t already pointed there), and then run the script for
you. Use this method to run your test.m script again.
2.3 Input and Output 11

Clear and Close All


You should nearly always begin your scripts with the following two commands:
clear;
close all;

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.

Making Matlab Be Quiet


Any line in a script that ends with a semicolon will execute without printing
to the screen. For example, add these two lines of code to your test script
a=sin(5);
b=cos(5)

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

in the command window, or looking in the workspace window. Printing output to


the command window takes time (a lot of time when dealing with big
¼ Neglecting to end lines
matrices), so your scripts will run faster if you end your lines with
with semicolons can lead to
semicolons. slow execution

2.3 Input and Output


For some scripts, it is sufficient to type the input in the script file before you
run it and view the output in the command window by judiciously leaving off
semicolons in your code. But often you will need to have the program get
input from the user as it runs and present formatted output on the screen.

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)
'

fprintf( ' x =%1.12g \n ,pi) '

fprintf( ' x =%1.10e \n ,pi) '

fprintf( ' x =%6.2f \n ,pi)'

fprintf( ' x =%12.8f y =%12.8f \n ,5,exp(5))


'

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

then the Matlab command

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

Listing 2.1 (ch2ex1.m)


clear; close all; t All the numbered code
listings are available on the
% build an array of x-values from 0 to 1 in steps of 0.1 Physics 330 course website.
x=0:.1:1;

% check the length of the x array


N=length(x)

% build a 2xN matrix with a row of x and a row of exp(x)


y=[x;exp(x)];

% Open a file in which to write the matrix - fid is a unit


% number to be used later when we write the file and close it.
% There is nothing special about the name fid - fxd works too,
% and, in fact, any variable is OK.
fid=fopen( file1.txt , w )
' ' ' '

% write the matrix to the file - note that it will be in the


% current Matlab directory. Type cd to see where you are.
% Matlab writes the file as two columns instead of two rows.
fprintf(fid, %6.2f
' %12.8f \r\n ,y)
'

% close the file


st=fclose(fid);

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.

Summing a series with a for loop

Let’s do the sum


X
N 1
(4.1)
n=1 n2
with N chosen to be a large
number.
Listing 4.1 (ch4ex1.m)

clear; close all;

% set s to zero so that 1/n^2 can be repeatedly added to it


s=0;
N=10000; % set the upper limit of the sum
for n=1:N % start of the loop

s = s + 1/n^2; % add 1/n^2 to s each iteration

end % end of the loop


fprintf( Sum = %g \n ,s) % print the answer
' '

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)

clear; close all;

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

% Now let s plot S vs. m


'

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);

(but we are practicing loops here).

Products with a for loop

Let’s calculate N ! = 1 · 2 · 3 · · · (N − 1) · N using a for loop that starts at n = 1


and ends at n = N , doing the proper multiply at each step of the way.
Listing 4.3 (ch4ex3.m)
clear; close all;

P=1; % set the first term in the product


N=20; % set the upper limit of the product

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

fprintf( ' N! = %g \n ,P)


' % print the answer

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)

Recursion relations with for loops


Suppose that we were solving a differential equation by substituting into it
a power series of the form ∞
X
f (x) = an xn (4.3)
n=1
and that we had discovered that the coefficients an satisfied the recursion relation

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

Listing 4.4 (ch4ex4.m)


clear; close all;

a(1)=1; % put the first element into the array


N=19; % the first one is loaded, so let s load 19 more
'

for n=1:N % start the loop


a(n+1)=(2*n-1)/(2*n+1)*a(n); % the recursion relation
end

disp(a) % display the resulting array of values

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;

term=1 % load the first term in the sum, 1/1^2=1


s=term; % load s with this first term

% start of the loop - set a counter n to one

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

fprintf( ' Sum = %g \n ,s)


'

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;

term=1; % load the first term in the sum, 1/1^2=1


s=term; % load s with this first term

% start of the loop - set a counter n to one


n=1;

while term > 1e-100 % set a ridiculously small term.


% Don t really do this, as you
'
24 Chapter 4 Loops and Logic

% only have 15 digits of precision.

n=n+1; % add 1 to n so that it will count: 2,3,4,5,...


term=1/n^2;
s=s+term;

if (n > 1000) % Break stop if it is taking too long


disp( This is taking too long. I m out of here... )
' '' '

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.

7.1 Inline Functions


Matlab will let you define expressions inside a script for use as functions
within that script only. For instance, if you wanted to use repeated references
to the function
sin( xy ) (7.1)
f (x, y )= 2
x + y2
you would use the following syntax (to make both a line plot in x with y = 2 and
to make a surface plot):
Listing 7.1 (ch7ex1.m)

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.

7.2 M-file Functions


M-file functions are subprograms stored in text files with .m extensions. A
func- tion is different than a script in that the input parameters it needs are
passed to it with argument lists like Matlab commands; for example, think
about sin(x) or plot(x,y, r- ). Here is an example of how you can code the
' '

function in (7.1) as an m-file function rather than inline function.

39
40 Chapter 7 Make Your Own Functions: Inline and M-files

Listing 7.2 (trig.m)


function f=trig(x,y)

f=sin(x.*y)./(x.^2+y.^2);

The first line of the function file is of the form

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

7.3 Functions With Multiple Outputs


Here is an example of a function that returns more than one output variable. This
function takes as input an integer n, a width a in nanometers, and an integer
NPoints and returns the energy level and wavefunction for a infinite square well
of width a.
Listing 7.4 (SquareWell.m)
function [x,psi,E] = SquareWell(n,a,NPoints)
% Calculate the energy and wavefunction for an
% electron in an infinite square well
%
% Inputs: n is the energy level; must be a positive integer
% a is the well width in nanometers
% NPoints is the number of points in the x grid
%
% Outputs: x is the grid for the plot, measured in nanometers
% psi is the normalized wave function
% E is the energy of the state in electron-volts

% Make the x-grid


xmin = 0;
xmax = a;
x = linspace(xmin,xmax,NPoints);

% Wave number for this energy level


k = n * pi / a;

% Calculate the wave function


psi = sqrt(2/a) * sin(k*x);

% Constants in MKS units


hbar = 1.05e-34;
m=9.11e-31;

% Calculate energy in electron-volts


E = n^2*pi^2*hbar^2 / (2*m*(a*1e-9)^2) / 1.6e-19;

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;

% remember that n must be a positive integer


n=3;

% Set the width to an Angstrom


a=0.1;
42 Chapter 7 Make Your Own Functions: Inline and M-files

% Get the values


[x,psi,Energy] = SquareWell(n,a,100);

% Make the plot and label it


plot(x,psi)
s=sprintf( \\Psi_%g(x); a=%g nm; Energy=%g eV ,n,a,Energy);
' '

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.

8.1 Solve a Linear System

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,

which is solved by (x, y, z) = (1, 2, 3), is handled in Matlab by defining a matrix A


corresponding to the coefficients on the left side of this equation and a column
vector b corresponding to the coefficients on the right like this
A=[ 1, 0,1
-1, 1,1
1,-1,1 ];
b=[4
4
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

8.2 Matrix Operations


Matrix Inverse
The inv command will compute the inverse of a square matrix. For instance,
using the matrix
A=[1,0,-1;-1,1,1;1,-1,1]

we load C with the inverse of A like this


C=inv(A)

We can verify by matrix multiplication that A*C is the identity matrix


A*C

43
44 Chapter 8 Linear Algebra and Polynomials

Transpose and Hermitian Conjugate


To find the transpose of the matrix A just use a single quote with a period, like this
A. '

To find the Hermitian conjugate of the matrix A (transpose of A with all


elements replaced with their complex conjugates) type
A '

(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)

Eigenvalues and Eigenvectors


To build a column vector containing the eigenvalues of the matrix A in the previ-
ous section use
E=eig(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

the zeros matrix

Z=zeros(5,5) % load Z with a 5x5 matrix full of zeros

the ones matrix

X=ones(3,3) % load X with a 3x3 matrix full of ones

and the random matrix

% load Y with a 4x6 matrix of random numbers between 0 and 1


% The random numbers are uniformly distributed on [0,1]
Y=rand(4,6)

% load Y with a 4x6 matrix of random numbers with a Gaussian


% distribution with zero mean and a variance of 1
Y=randn(4,6)

% And to load a single random number just use


r=rand

8.3 Vector Operations


Dot and Cross Products
Matlab will do vector dot and cross products for you with the commands dot and
cross, like this:
46 Chapter 8 Linear Algebra and Polynomials

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.

Norm of Vector (Magnitude)


Matlab will compute the magnitude of a vector a (the square root of the sum
of the squares of its components) with the norm command
a=[1,2,3]
norm(a)

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)

Find the polynomial from the roots


If you know that the roots of a polynomial are 1, 2, and 3, then you can find
the polynomial in Matlab’s array form this way
r=[1,2,3];
p=poly(r)
8.4 Polynomials 47

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)

Stare at this result and make sure that it is correct.

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

% now divide b into a finding the quotient and remainder


[q,r]=deconv(a,b)

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

First Derivative = x+ . (8.2)


x+ 1 x+ 1
Matlab can take a polynomial array and return the polynomial array of its deriva-
tive:
a=[1,1,1,1]
ap=polyder(a)

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];

% load the x-values


x=-5:.01:5;

% evaluate the polynomial


y=polyval(a,x);

% plot it
plot(x,y)
Chapter 9
Fitting Functions to Data

A common problem that physicists encounter is to find the best fit of a


func- tion (with a few variable parameters) to a set of data points. If you are
fitting to a polynomial, then the easiest way to do this is with polyfit. But if
you want to fit to an arbitrary functions containing sines, cosines, exponentials,
logs, etc., then there is no simple prebuilt command available. Pay attention to
this section; it is useful.

9.1 Fitting Data to a Polynomial


If you have some data in the form of arrays (x, y ) (perhaps read in with
Matlab’s load command), Matlab will do a least-squares fit of a polynomial
of any order you choose to this data. In this example we will let the data be
the sine function between 0 and π and we will fit a polynomial of order 4 to it.
Then we will plot the two functions on the same frame to see if the fit is any
good. Before going on to the next section, try fitting a polynomial of order 60
to the data to see why you need to be careful when you do fits like this.
Listing 9.1 (ch9ex1.m)

clear; close all;

x=linspace(0,pi,50);

% make a sine function with 1% random error on it f=sin(x)


+.01*rand(1,length(x));

% fit to the data


p=polyfit(x,f,4);

% evaluate the fit


g=polyval(p,x);

% plot fit and data


together
plot(x,f, r* ,x,g, b- )
' ' ' '

9.2 General Fits with fminsearch

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

to an exponential function with two adjustable parameters a1 and a2


x
f (x, a1, a2) = a1ea2 . (9.1)
The first step in the fitting process is to make a m-file function, call it funcfit.m,
that evaluates the function you want to fit to, like this
Listing 9.2 (funcfit.m)
function f=funcfit(a,x)
% this function evaluates the fitting
% function f(x,a1,a2,a3,...) to be fit to
% data. It is called by leastsq.

% a is a vector of variable fitting parameters a1, a2, ...


% that are used in the function and x is a
% vector of x-values

% the function returns a vector f=f(x,a1,a2,...)

% sample exponential function with 2 variable


% parameters
f = a(1)*exp(a(2)*x);

The input a is a matrix containing the as-yet unknown parameters and x is a


matrix with the independent variable for your fit. Make sure the funcfit.m
function works properly on matrices, so that if x is a matrix input then f is a
matrix of function values.
Our goal is to write some code to choose the parameters (a1, a2, a3, ...) in such
a way that the sum of the squares of the differences between the function and the
data is minimized, or in mathematical notation we want to minimize the quantity
N
X
S= ( f (xj ) − y j )2 . (9.2)
j=1

We need to make another Matlab M-file called leastsq.m which evaluates


the least-squares sum you are trying to minimize. It needs access to your
fitting function f (x, a), which you stored in the Matlab M-file funcfit.m above.
Here is the form of the leastsq.m function.
Listing 9.3 (leastsq.m)
function s=leastsq(a,x,y)

% leastsq can be passed to fminsearch to do a


% non-linear least squares fit of the function
% funcfit(a,x) to the data set (x,y).
% funcfit.m is built by the user as described here

% a is a vector of variable parameters; x and y


% are the arrays of data points

% find s, the sum of the squares of the differences


9.2 General Fits with fminsearch 51

% between the fitting function and the 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

% read the data file and load x and y


load data.fil;
x=data(:,1);
y=data(:,2);

% set up for the plot of the fitting function


xmin=min(x);
xmax=max(x);
npts=1001;
dx=(xmax-xmin)/(npts-1);
52 Chapter 9 Fitting Functions to Data

xplot=xmin:dx:xmax;

% set ifit to 0 and don t continue on to the fit until


'

% the user sets it to 1


ifit=0;
while (ifit==0)

disp( Enter an initial guess for the function )


' '

a=input( parameters [a1,a2,...] in vector form [...]-


' ' )

% plot the data and the initial function guess


yplot=funcfit(a,xplot);

plot(x,y, b* ,xplot,yplot, r- )
' ' ' '

xlabel( x ) ' '

ylabel( y ) ' '

title( Initial Guess and Data )


' '

ifit=input( 0:guess again; 1:fit with this guess -


' ' )

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); ' '

% Have fminsearh look for the best parameters to minimize the


% leastsq.m function. The @ character in front of the function
% name tells Matlab it is a reference to an m-file function
a=fminsearch(@leastsq,a,option,x,y)

% Evaluate the function with the final fit parameters


yplot=funcfit(a,xplot);

% Plot the final fit and the


data
plot(x,y, b* ,xplot,yplot, r- )
' ' ' '

xlabel( x )
' '

ylabel( y )' '

title( Final Fit and Data )


' '

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

You might also like