Baixe Numerical Analysis with MATLAB e outras Notas de estudo em PDF para Matemática, somente na Docsity!
MATLAB has many tools that make this package well suited for numerical computations. This
tutorial deals with the rootfinding, interpolation, numerical differentiation and integration and
numerical solutions of the ordinary differential equations. Numerical methods of linear algebra
are discussed in Tutorial 4.
Function Description
abs Absolute value
dblquad Numerically evaluate double integral
erf Error function
feval Execute function specified by string
fzero Scalar nonlinear zero finding
gamma Gamma function
inline Construct INLINE object
interp1 One-dimensional interpolation
interp2 Two-dimensional interpolation
linspace Evenly spaced vector
meshgrid X and Y arrays for 3-D plots
norm Matrix or vector norm
ode23 Solve non-stiff differential equations
ode45 Solve non-stiff differential equations
ode113 Solve non-stiff differential equations
ode15s Solve stiff differential equations
ode23s Solve stiff differential equations
poly Convert roots to polynomial
polyval Evaluate polynomial
ppval Evaluate piecewise polynomial
quad Numerically evaluate integral, low order method
quad8 Numerically evaluate integral, higher order method
rcond Reciprocal condition estimator
roots Find polynomial roots
spline Cubic spline data interpolation
surf 3-D colored surface
unmkpp Supply details about piecewise polynomial
! " #
A central problem discussed in this section is formulated as follows. Given a real-valued function
f: n^ n , n 1 , find a vector r so that f(r) = 0. Vector r is called the root or zero of f.
5.2.1 Computing roots of the univariate polynomials
Polynomials are represented in MATLAB by their coefficients in the descending order of powers.
For instance, the cubic polynomial p(x) = 3x^3 + 2x^2 - 1 is represented as
p = [3 2 0 1];
Its roots can be found using function roots
format long
r = roots(p)
r = -1. 0.16666666666667 + 0.55277079839257i 0.16666666666667 - 0.55277079839257i
To check correctness of this result we evaluate p(x) at r using function polyval
err = polyval(p, r)
err = 1.0e-014 *
0 + 0.01110223024625i 0 - 0.01110223024625i
To reconstruct a polynomial from its roots one can use function poly. Using the roots r computed
earlier we obtain
poly(r)
ans = 1.00000000000000 0.66666666666667 0.
Let us note that these are the coefficients of p(x) all divided by 3. The coefficients of p(x) can be
recovered easily
3*ans
ans = 3.00000000000000 2.00000000000000 0.
r = fzero('f1', [0 1])
r =
However, this choice of the designated interval
fzero('f1', [1 2])
¨??? Error using ==> fzero The function values at the interval endpoints must differ in sign.
generates the error message.
By adding the third input parameter tol you can force MATLAB to compute the zero of a
function with the relative error tolerance tol. In our example we let tol = 10 -3^ to obtain
rt = fzero('f1', .5, 1e-3)
rt =
A relative error in the computed zero rt is
rel_err = abs(rt-r)/r
rel_err = 2.969162630892787e-
Function fzero takes fourth optional parameter. If it is set up to 1, then the iteration information is
displayed. Using function f1 , with x0 = 0.5 , we obtain
format short
rt = fzero('f1', .5, eps, 1)
Func evals x f(x) Procedure 1 0.5 0.377583 initial 2 0.485858 0.398417 search 3 0.514142 0.356573 search 4 0.48 0.406995 search 5 0.52 0.347819 search 6 0.471716 0.419074 search 7 0.528284 0.335389 search 8 0.46 0.436052 search 9 0.54 0.317709 search 10 0.443431 0.459853 search 11 0.556569 0.292504 search 12 0.42 0.493089 search 13 0.58 0.256463 search 14 0.386863 0.539234 search 15 0.613137 0.20471 search 16 0.34 0.602755 search 17 0.66 0.129992 search 18 0.273726 0.689045 search
19 0.726274 0.0213797 search 20 0.18 0.803844 search 21 0.82 -0.137779 search
Looking for a zero in the interval [0.18, 0.82]
22 0.726355 0.0212455 interpolation 23 0.738866 0.00036719 interpolation 24 0.739085 -6.04288e-008 interpolation 25 0.739085 2.92788e-012 interpolation 26 0.739085 0 interpolation rt =
We have already seen that MATLAB function roots had faild to produce satisfactory results
when computing roots of the polynomial p(x) = (x – 2) 5. This time we will use function fzero to
find a multiple root of p(x). We define a new function named f
function y = f2(x)
y = (x - 2)^5;
and next change format to
format long
Running function fzero we obtain
rt = fzero('f2', 1.5)
rt =
This time the result is as expected.
Finally, we will apply function fzero to compute the multiple root of p(x) using an expanded
form of the polynomial p(x)
function y = f3(x)
y = x^5 - 10x^4 + 40x^3 -80x^2 + 80x - 32;
rt = fzero('f3', 1.5)
rt =
Again, the computed approximation of the root of p(x) has a few correct digits only.
has the exact zeros r = [0 1] T^ and r = [2 0] T^ (see [6], p. 166). Functions fun1 and J1 define the
system of equations and its Jacobian, respectively
function z = fun1(x)
z = zeros(2,1); z(1) = x(1) + 2x(2) - 2; z(2) = x(1)^2 + 4x(2)^2 - 4;
function s = J1(x)
s = [1 2;2x(1) 8x(2)];
Let
x0 = [0 0];
Then
[r, iter] = NR('fun1', 'J1', x0, eps, eps, 10)
¨??? Error using ==> nr Try a new initial approximation x
For x0 as chosen above the associated Jacobian is singular. Let's try another initial guess for r
x0 = [1 0];
[r, niter] = NR('fun1', 'J1', x0, eps, eps, 10)
r =
-0. niter = 5
Consider another nonlinear system
f 1(x) = x 1 + x 2 –
f 2(x) = sin(x 12 + x 22 ) – x 1.
The m-files needed for computing its zeros are named fun2 and J
function w = fun2(x);
w(1) = x(1) + x(2) - 1; w(2) = sin(x(1)^2 + x(2)^2) - x(1); w = w(:);
function s = J2(x)
s = [1 1; 2x(1)cos(x(1)^2 + x(2)^2)-1 2x(2)cos(x(1)^2 + x(2)^2)];
With the initial guess
x0 = [0 1];
the zero r is found to be
[r, niter] = NR('fun2', 'J2', x0, eps, eps, 10)
r =
niter = 5
while the initial guess
x0 = [1 1];
[r, iter] = NR('fun2', 'J2', x0, eps, eps, 10)
r = -0.
iter = 10
gives another solution. The value of function fun2 at the computed zero r is
feval('fun2', r)
ans = 1.0e-015 * 0 -0.
Implementation of other classical methods for computing the zeros of scalar equations, including
the fixed-point iteration, the secant method and the Schroder method are left to the reader (see
Problems 3, 6, and 12 at the end of this tutorial).
$ % & ' (
Interpolation of functions is one of the classical problems in numerical analysis. A one
dimensional interpolation problem is formulated as follows.
Given set of n+1 points xk , y k , 0 k n , with x 0 < x 1 < … < xn , find a function f(x) whose
graph interpolates the data points, i.e., f(xk) = y k , for k = 0, 1, …, n.
0 0.5 1 1.5 2 2.5 3 3.
-0.
-0.
-0.
-0.
0
1
Piecewise constant interpolant of y = sin(2x)
yi = interp1(x, y, xi, 'cubic');
plot(x, y, 'o', xi, yi), title('Cubic interpolant of y = sin(2x)')
0 0.5 1 1.5 2 2.5 3 3.
-0.
-0.
-0.
-0.
0
1
Cubic interpolant of y = sin(2x)
5.3.2 Interpolation by algebraic polynomials
Assume now that the interpolating function is an algebraic polynomial pn(x) of degree at most n ,
where n = number of points of interpolation – 1. It is well known that the interpolating
polynomial pn always exists and is unique (see e.g., [6], [9]). To determine the polynomial
interpolant one can use either the Vandermonde's method or Lagrange form or Newton's form or
Aitken's method. We shall describe briefly the Newton's method.
We begin writing p(x) as
(5.3.1) pn(x) = a 0 + a1(x – x0) + a 2 (x – x0)(x – x1) + … + an(x – x0)(x – x1) … (x – xn-1 )
Coefficients a 0 , a 1 , … , a n are called the divided differences and they can be computed
recursively. Representation (5.3.1) of pn(x) is called the Newton's form of the interpolating
polynomial. The k-th order divided difference based on points x 0 , … xk , denoted by [x 0 , … , xk] ,
is defined recursively as
[xm] = y m if k = 0
[x0, … , x k] = ([x1, … , x k] – [x0, … , xk-1])/(xk – x0) if^ k > 0.
Coefficients {a k} in representation (5.3.1) and the divided differences are related in the following
way
a k = [x0, … , x k].
Function Newtonpol evaluates an interpolating polynomial at the user supplied points.
function [yi, a] = Newtonpol(x, y, xi)
% Values yi of the interpolating polynomial at the points xi. % Coordinates of the points of interpolation are stored in % vectors x and y. Horner's method is used to evaluate % a polynomial. Second output parameter a holds coeeficients % of the interpolating polynomial in Newton's form.
a = divdiff(x, y); n = length(a); val = a(n)ones(length(xi)); for m = n-1:-1: val = (xi - x(m)).val + a(m); end yi = val(:);
function a = divdiff(x, y)
% Divided differences based on points stored in arrays x and y.
n = length(x); for k=1:n-
for k=1:m n = input('Enter degree of the interpolating polynomial '); hold on x = linspace(-5,5,n+1); y = 1./(1 + x.*x); z = linspace(-5.5,5.5); t = 1./(1 + z.^2); h1_line = plot(z,t,'-.'); set(h1_line, 'LineWidth',1.25) t = Newtonpol(x,y,z); h2_line = plot(z,t,'r'); set(h2_line,'LineWidth',1.3,'Color',[0 0 0]) axis([-5.5 5.5 -.5 1]) title(sprintf('Example of divergence (n = %2.0f)',n)) xlabel('x') ylabel('y') legend('y = 1/(1+x^2)','interpolant') hold off end
Typing showint in the Command Window you will be prompted to enter value for the parameter
m = number of interpolating polynomials you wish to generate and also you have to enter
value(s) of the degree of the interpolating polynomial(s). In the following example m = 1 and
n = 9
Divergence occurs at points that are close enough to the endpoints of the interval of interpolation
[-5, 5].
We close this section with the two-point Hermite interpolaion problem by cubic polynomials.
Assume that a function y= g(x) is differentiable on the interval [ a, b]. We seek a cubic
polynomial p3(x) that satisfies the following interpolatory conditions
(5.3.2) p3(a) = g(a), p 3(b) = g(b), p 3'(a) = g'(a), p 3 '^ (b) = g'(b)
Interpolating polynomial p3(x) always exists and is represented as follows
(5.3.3) p3(x) = (1 + 2t)(1 - t)
2
g(a) + (3 - 2t)t
2
g(b) + h[t(1 - t)
2
g'(a) + t
2
(t - 1)g'(b)] ,
where t = (x - a)/(b - a) and h = b – a.
Function Hermpol evaluates the Hermite interpolant at the points stored in the vector xi.
function yi = Hermpol(ga, gb, dga, dgb, a, b, xi)
% Two-point cubic Hermite interpolant. Points of interpolation % are a and b. Values of the interpolant and its first order % derivatives at a and b are equal to ga, gb, dga and dgb, % respectively. % Vector yi holds values of the interpolant at the points xi.
h = b – a; t = (xi - a)./h; t1 = 1 - t; t2 = t1.t1; yi = (1 + 2t).t2ga + (3 - 2t).(t.t)gb +… h.(t.t2dga + t.^2.(t - 1)dgb);
In this example we will interpolate function g(x) = sin(x) using a two-point cubic Hermite
interpolant with a = 0 and b = /
xi = linspace(0, pi/2);
yi = Hermpol(0, 1, 1, 0, 0, pi/2, xi);
zi = yi – sin(xi);
plot(xi, zi), title('Error in interpolation of sin(x) by a two-point cubic Hermite polynomial')
MATLAB's command yi = spline(x, y, xi) evaluates cubic spline s(x) at points stored in the array
xi. Vectors x and y hold coordinates of the points to be interpolated. To obtain the piecewise
polynomial representation of the spline interpolant one can execute the command
pp = spline(x, y). Command zi = ppval(pp, xi) evaluates the piecewise polynomial form of the
spline interpolant. Points of evaluation are stored in the array xi. If a spline interpolant has to be
evaluated for several vectors xi , then the use of function ppval is strongly recommended.
In this example we will interpolate Runge's function g(x) = 1/(1 + x^2 ) on the interval [0, 5] using
six evenly spaced breakpoints
x = 0:5;
y = 1./(1 + x.^2);
xi = linspace(0, 5);
yi = spline(x, y, xi);
plot(x, y, 'o', xi, yi), title('Cubic spline interpolant')
0 1 2 3 4 5
0
1
Cubic spline interpolant
The maximum error on the set xi in approximating Runge's function by the cubic spline we found
is
err = norm(abs(yi-1./(1+xi.^2)),'inf')
err =
Detailed information about the piecewise polynomial representation of the spline interpolant can
be obtained running function spline with two input parameters x and y
pp = spline(x, y);
and next executing command unmkpp
[brpts, coeffs, npol, ncoeff] = unmkpp(pp)
brpts = 0 1 2 3 4 5 coeffs = 0.0074 0.0777 -0.5852 1. 0.0074 0.1000 -0.4074 0. -0.0371 0.1223 -0.1852 0. -0.0002 0.0110 -0.0519 0. -0.0002 0.0104 -0.0306 0. npol = 5 ncoeff = 4
The output parameters brpts , coeffs , npol , and ncoeff represent the breakpoints of the spline
interpolant, coefficients of s(x) on successive subintervals, number of polynomial pieces that
constitute spline function and number of coefficients that represent each polynomial piece,
respectively. On the subinterval [xl, xl+1 ] the spline interpolant is represented as
s(x) = c l1(x – xl) 3 + cl2 (x – xl) 2 + cl3 (x – xl) + c l
where [c l1 c l2 c l3 c l4] is the lth row of the matrix coeffs. This form is called the piecewise
polynomial form ( pp–form ) of the spline function.
Differentiation of the spline function s (x) can be accomplished running function splder. In order
for this function to work properly another function pold (see Problem 19) must be in MATLAB's
search path.
function p = splder(k, pp, x)
% Piecewise polynomial representation of the derivative % of order k (0 <= k <= 3) of a cubic spline function in the % pp form with the breakpoints stored in the vector x.
m = pp(3); lx4 = length(x) + 4; n = pp(lx4); c = pp(1 + lx4:length(pp))'; c = reshape(c, m, n); b = pold(c, k); b = b(:)';
% the descending order of powers.The output parameter pts holds % the points of the union of two sets x and xi.
n = length(x); [p, q] = size(A); if n-1 ~= p error('Vector t and matrix A must be "compatible"') end yi = []; pts = union(x, xi); for m=1:p l = find(pts == x(m)); r = find(pts == x(m+1)); if m < n- yi = [yi polyval(A(m,:), pts(l:r-1))]; else yi = [yi polyval(A(m,:), pts(l:r))]; end end
In this example we will evaluate and plot the graph of the piecewise linear function s(x) that is
defined as follows
s(x) = 0, if |x| 1
s(x) = 1 + x, if -1 x 0
s(x) = 1 – x, if 0 x 1
Let
x = -2:2;
xi = linspace(-2, 2);
A = [0 0;1 1;1 –1;0 0];
[pts, yi] = evalppf(x, xi, A);
plot(pts, yi), title('Graph of s(x)'), axis([-2 2 -.25 1.25])
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
-0.
0
1
Graph of s(x)
$ & ' (
The interpolation problem discussed in this section is formulated as follows.
Given a rectangular grid {xk, yl} and the associated set of numbers zkl , 1 k m, 1 l n , find
a bivariate function z = f(x, y) that interpolates the data, i.e., f(xk. y l) = zkl for all values of k and l.
The grid points must be sorted monotonically, i.e. x 1 < x 2 < … < xm with a similar ordering of the
y-ordinates.
MATLAB's built-in function zi = interp2(x, y, z, xi, yi, 'method') generates a bivariate
interpolant on the rectangular grids and evaluates it in the points specified in the arrays xi and yi.
Sixth input parameter 'method' is optional and specifies a method of interpolation. Available
methods are:
- 'nearest' - nearest neighbor interpolation
- 'linear' - bilinear interpolation
- 'cubic' - bicubic interpolation
- 'spline' - spline interpolation
In the following example a bivariate function z = sin(x^2 + y^2 ) is interpolated on the square
–1 x 1 , -1 y 1 using the 'linear' and the 'cubic' methods.
[x, y] = meshgrid(-1:.25:1);
z = sin(x.^2 + y.^2);
[xi, yi] = meshgrid(-1:.05:1);