Matlab Number
Matlab Number
Introduction to M-files
In this tutorial we learn the basics of working with M-files in M ATLAB, so called because they must use
“.m” for their filename extension. There are two types of M-files:
• A script is a collection of M ATLAB commands which are executed just as if they had been typed in
at the command line. When the script is finished running, any variables defined in the script are still
available in the current M ATLAB command-line environment.
Executing M ATLAB commands from within a script, even for relatively simple tasks, makes it much
easier to reproduce results later, or to rerun the same calculations with different parameter settings. At
the same time the script serves as a record of your activity and can serve as a useful starting point for
future projects.
• A function accepts input arguments and returns output arguments, similar to functions in structured
programming languages such as JAVA, C, and F ORTRAN. Variables defined in a function are local to
the function. The variables created in the function are not directly accessible from the command line
once the function completes execution.
The Windows version of M ATLAB provides a text editor for creating and modifying M-files. Throughout
this document it is assumed that the reader is running the student version of M ATLAB 6 on the Windows
platform. In this case the default working directory is typically C:\matlab_sv12\work and the M-file
editor will save the M-files to this directory unless the user specifies otherwise.1 The M ATLAB principles
will be introduced in the context of learning several methods of numerical integration. At the end of the
tutorial we will have produced M ATLAB code that can be used to approximate definite integrals.
Numerical integration
Rb
To approximate the definite integral a f (x) d x we first divide the interval [a, b] into n subintervals, each
of length h = (b − a)/n. The endpoints of the subintervals are denoted by the points x1 , x2 , . . . , xn+1 ,
where x1 = a and xn+1 = b. We write yi to denote the evaluation of f (x) at node xi , yi = f (xi ). The
i th subinterval is given by [xi , xi+1 ], with xi+1 − xi = h, for i = 1, . . . , n. [The endpoints are indexed as
1, 2, . . . , n + 1 to coincide with the indexing of array elements in Matlab. In the textbook the grid points are
indexed as 0, 1, . . . , n.]
1 Use the pwd command to confirm the current working directory. To change the current directory, enter cd dir_name from the
command line, or choose MATLAB → Current Directory from the M ATLAB Launch Pad.
1
For the right-endpoint approximation the height of the rectangle
for the interval [xi , xi+1 ] is given by f (xi+1 ), the value of the
function at the right endpoint.
b n
. Right−Endpoint Approx (n=8)
Z X
f (x) d x ≈ hyi+1 = h y2 + y3 + · · · + yn+1 = Rn
a i=1 x1 x2 xn xn+1
The trapezoidal rule uses n trapezoids of width h to approximate the definite integral. The top edge of the
trapezoid for the subinterval [xi , xi+1 ] is the line segment connecting the two points (xi , yi ) and (xi+1 , yi+1 ).
The area of the i th trapezoid is given by Ai = h(yi + yi+1 )/2. Summing over the n trapezoids,
b n
.
Z X h h
f (x) d x ≈
yi + yi+1 = y1 + 2y2 + 2y3 + · · · + 2yn + yn+1 = Tn (1)
a i=1
2 2
The trapezoidal rule is equivalent to averaging the left-endpoint and right-endpoint approximations,
Tn = L n + Rn /2 .
(2)
Note: When copying commands from this document into your own M-files or to the command line, the
percent sign (%) marks the rest of the line as a comment. It is not necessary to copy the comments.
To create a new M-file, select File → New → M-file from the menu bar. The M-file editor starts up with an
empty window. Copy the following M ATLAB commands into the new M-file.
a = 0.0; b = 1.0; % integrate f(x) from a=0 to b=1
n = 8; % number of subintervals; n EVEN
h = (b - a) / n; % width of subintervals
2
for i = 1:n % i = 1, 2, ..., n-1, n
x(i+1) = x(i) + h; % x(2)=x(1)+h; x(3)=x(2)+h; ...
y(i+1) = 4 / (1 + x(i+1)ˆ2); % y(i) = 4 / (1 + x(i)*x(i))
end
The function fprintf is for writing formatted data to a file.2 To save the new M-file to the disk, choose
File → Save from the editor’s pull-down menu and follow the dialog box. To test the new script, enter the
name of the script from the Command Window. This writeup assumes the script has been named m2s.m. If
M ATLAB reports an error, use the editor to make the corrections, save the revised file, and rerun m2s. Once
the program is working correctly you should see the following output:
>> m2s
n = 8
Ln = 3.263988494491 error= 1.22e-01
Rn = 3.013988494491 error= -1.28e-01
Tn = 3.138988494491 error= -2.60e-03
The first line of the file identifies m2f as a function that can be called with a single input argument. The input
value will be copied to the variable n inside the function. The contents of the variable Tn are returned to the
2 With the first argument of fprintf set to 1 the output goes to the Command Window. The second argument is a string for
specifying the output format. For example, %d specifies decimal integer output, %.12f specifies real numbers with twelve digits to
the right of the decimal point, %.2e specifies exponential notation with two digits to the right of the decimal point (three significant
digits), and \n produces a linefeed.
3
program that called m2f (just the Command Window in this case). After saving these changes, run the new
function for different values of n. For example, pass the number 8 to duplicate the earlier results.
>> m2f(8)
n = 8
Ln = 3.263988494491 error= 1.22e-01
Rn = 3.013988494491 error= -1.28e-01
Tn = 3.138988494491 error= -2.60e-03
ans =
3.1390
Calling the function with the command S = m2f(8) will save the output in the variable S.
Exercise 1 : Run your function m2f.m using increasing values of the input argument p. What is the
smallest value of n that makes the absolute value of the error in Tn less than 10−6 ? Less than 10−8 ?
Summing the areas from the n/2 rectangles yields the midpoint approximation:
b n/2
.
Z X
f (x) d x ≈ 2hy2k = 2h y2 + y4 + · · · + yn−2 + yn = Mn (4)
a k=1
To include the midpoint approximation in your M ATLAB function, add the following code3 to the function
m2f.m. This new for loop can be added just after the calculation of Tn.
Exercise 2 : Run m2f.m and compare the accuracy of the midpoint and trapezoidal approximations for
several values of the input argument n. Comment on your observations.
Simpson’s rule
In each of these integration methods the approximation formula is just the definite integral for a simple
function that approximates f (x). For example, the trapezoidal rule uses a piecewise linear function. On
3 It is ALWAYS a good idea to first make a copy of the existing program before adding new features. If you are unable to get the
revisions to work properly, you can still return to a working version of the program.
4
each subinterval [xi , xi+1 ] we integrate a linear function in place of f (x). The approximating function is
piecewise because the equation of the linear function changes from one subinterval to the next. Each of the
other three methods use piecewise constant functions to approximate f (x).
With this point of view, we look to improve the accuracy of the numerical integration by approximating
f (x) with a higher order polynomial. On each subinterval [x2k−1 , x2k+1 ] of length 2h, there is exactly one
second-order polynomial that passes through the three points (x2k−1 , y2k−1 ), (x2k , y2k ), and (x2k+1 , y2k+1 ).
The area under this polynomial is given by Ak = 2h(y2k−1 + 4y2k + y2k+1 )/6, for k = 1, 2, . . . , n/2.
Summing these areas (there are n/2 subintervals of length 2h) results in Simpson’s Rule:
b n/2
.
Z X h h
f (x) d x ≈
y2k−1 + 4y2k + y2k+1 = y1 + 4y2 + 2y3 + 4y4 + · · · + 4yn + yn+1 = Sn (5)
a k=1
3 3
Simpson’s rule can also be expressed as a weighted average of the trapezoidal and midpoint rules.
Sn = 2Tn + Mn /3
(6)
Exercise 3 : Add the calculation for Simpson’s rule from equation (6) to the function m2f.m, including
an additional fprintf statement and error calculation. Change the function so it returns the value of the
Simpson approximation rather than the trapezoidal approximation. Compare the accuracy of the different
integration methods. What is the smallest value of n that makes the absolute value of the error in Sn less than
10−6 ? Less than 10−8 ?
R4 2
Exercise 4 : Modify the function m2f.m to estimate the definite integral 0 e−x d x using Simpson’s
approximation. Calculate the Simpson approximation for increasing values of n = {2, 4, 8, 16, . . .} until
the difference |Sn − Sn/2 | < 10−10 . In this exercise you must change in the M-file both the value of b and
the expressions for calculating y = f (x). The error calculations (Tn - pi,...) are no longer valid for this
exercise. The following code shows how one might proceed to call m2f once the function has been revised.
>> format long; % display more significant digits
>> s8 = m2f(8) % display Simpson approx with n = 8
ans = ...
>> s16 = m2f(16) % display Simpson approx with n = 16
ans = ...
>> abs(s16 - s8) % display the difference |S_16 - S_8|
ans = ...
>> ... % continue until difference < 1.0e-10
Record the final value of n, the estimate Sn with at least 12 significant digits, and the difference |Sn − Sn/2 |.
Exercise 5 : If R af (x) is any third-order polynomial, show that Simpson’s rule with n = 2 is exact for the
definite integral −a f (x) d x. In other words, verify the following equality:
Z a
h
(Ax 3 + Bx 2 + C x + D) d x =
y1 + 4y2 + y3
−a 3
First calculate the integral on the left-hand side in terms of the parameters A, B, C, D, and a. Then calculate
the right-hand side where yi = f (xi ) = Axi3 + Bxi2 + C xi + D. In evaluating the right-hand side, you must
first identify the value of h, and the nodes x1 , x2 , x3 , in terms of the parameter a. You should be able to show
that the two sides are equal for any choice of the constants A, B, C, D, and a.
[ This is one reason for the popularity of Simpson’s rule. We started by approximating the integrand with a
piecewise second-order polynomial and the method turns out to be exact for all third-order polynomials. ]