matlab_tools.pdf

4
MATLAB Tools from AMATH 352 We have studied many tools from numerical analysis this quarter in AMATH 352. MATLAB has many of these tools implemented in built-in functions. After studying and imple ment ing many of the tools this quarter, you should have an appreciation for how these tools work and in what situations it is appropriate to use them. Here’s a sample of a few functions and how you might use them. Root Finding Say you want to look for the zero of a function  f  x  cos  x  x. The se type s of pro ble ms ofte n arise when you are looking for equilibri a of dynamic al systems or roots of charac teris tic polynomia ls. In MATLAB, dene the function and use  fzero to nd the root. The function  fzero has two arguments: the func tion and a val ue to start from in looki ng for the root. It starts from that valu e, nds an interval over which the sign of the function changes and then uses a improved hybrid secant/bisection algorithm to nd the root. >> f = inline(’cos(x) - x’) f = Inlin e func tion: f(x) = cos(x) - x >> fzero(f,0) Zero found in the interval: [-0.9051, 0.9051]. ans = 0.7391 Root nding can be related to nding the minimum of a function . Minimizati on/ma ximiz ation is often enco unter ed in optimiza tion — perhaps in looki ng for the shap e of a wing that has the lowest drag/hig hest lift. MA TLAB searc hes for the minimum of a function of one vari able  fminbnd  and a function of many variables  fmins. The functio n  fminbnd has three arguments: a function and the left and right ends of the interval in which to search for the maximum. Let’s minimize  f  x  x exp  x 2 in the interval  x  0  10  : >> f = inline(’-x.*ex p(-x .ˆ2)’) f = Inlin e func tion: f(x) = -x.*exp(- x.ˆ2 ) >> fminbnd(f,0,10) Optimization terminated successfully: the current x satisfies the termination criteria using OPTIONS.TolX of 1.000000e-04 ans = 0.7071 You can look for the solution of a set of nonlinear equations  f  x  0  by looking for the minimum of the function g  x  f 2 1  x  f 2 2  x  f 2 n  x  . Let’s say we want to solve:  f 1  x  y  x 2  y 2 2  0  f 2  x  y  x 2  y  1  0 Construct the function g  x  y  and look for the minimum. The minimu m should be zero and the valu es of  x and y  at the minimum are the solution to the system of equations. The function fmins takes as arguments 1

Transcript of matlab_tools.pdf

Page 1: matlab_tools.pdf

7/27/2019 matlab_tools.pdf

http://slidepdf.com/reader/full/matlabtoolspdf 1/4

MATLAB Tools from AMATH 352

We have studied many tools from numerical analysis this quarter in AMATH 352. MATLAB has many

of these tools implemented in built-in functions. After studying and implementing many of the tools this

quarter, you should have an appreciation for how these tools work and in what situations it is appropriate to

use them. Here’s a sample of a few functions and how you might use them.

Root Finding

Say you want to look for the zero of a function f 

 

x¡ ¢

cos

 

x¡ ¤

x. These types of problems oftenarise when you are looking for equilibria of dynamical systems or roots of characteristic polynomials. In

MATLAB, define the function and use fzero to find the root. The function fzero has two arguments: the

function and a value to start from in looking for the root. It starts from that value, finds an interval over

which the sign of the function changes and then uses a improved hybrid secant/bisection algorithm to find

the root.

>> f = inline(’cos(x) - x’)

f =

Inline function:

f(x) = cos(x) - x

>> fzero(f,0)Zero found in the interval: [-0.9051, 0.9051].

ans =

0.7391

Root finding can be related to finding the minimum of a function. Minimization/maximization is often

encountered in optimization — perhaps in looking for the shape of a wing that has the lowest drag/highest

lift. MATLAB searches for the minimum of a function of one variable fminbnd and a function of many

variables fmins. The function fminbnd has three arguments: a function and the left and right ends of the

interval in which to search for the maximum. Let’s minimize f  

x¡ ¢ ¤

xexp 

¤x2

¡in the interval x

§ ¨0

10

:

>> f = inline(’-x.*exp(-x.ˆ2)’)f =

Inline function:

f(x) = -x.*exp(-x.ˆ2)

>> fminbnd(f,0,10)

Optimization terminated successfully: the current x satisfies the

termination criteria using OPTIONS.TolX of 1.000000e-04

ans =

0.7071

You can look for the solution of a set of nonlinear equations f  

x ¡ ¢ 0 by looking for the minimum of thefunction g

 

x¡ ¢

f 21

 

f 22

 

f 2n 

x¡. Let’s say we want to solve:

 f 1 

x y ¡ ¢ x2  y2 ¤2

¢0

 f 2 

xy

¡ ¢x2

¤ y

0

Construct the function g 

xy

¡and look for the minimum. The minimum should be zero and the values of x

and y at the minimum are the solution to the system of equations. The function fmins takes as arguments

1

Page 2: matlab_tools.pdf

7/27/2019 matlab_tools.pdf

http://slidepdf.com/reader/full/matlabtoolspdf 2/4

>> g = inline(’(x(1)ˆ2 + x(2)ˆ2 - 2)ˆ2 + (x(1)ˆ2 - x(2) + 1)ˆ2’)

g =

Inline function:

g(x) = (x(1)ˆ2 + x(2)ˆ2 - 2)ˆ2 + (x(1)ˆ2 - x(2) + 1)ˆ2

>> fmins(g,[0;0])

ans =0.5502

1.3028

>> g(ans)

ans =

4.8850e-09

The last computation insures that the answer is a zero of g (and also of  f ).

Polynomial interpolation and fitting

MATLAB has a set of functions which deal with polynomial interpolation and fitting together. The com-

mand polyfit(x,y,n) fits a polynomial of degree n to the data points 

xi yi ¡

where xi and yi are the ith compo-

nents of the vectors x and y. If you want to fit a line to the data in x an y, use p = polyfit(x,y,1) — a lineis a first degree polynomial. For a quadratic, use n = 2, etc. If you want to interpolate the points in x and y,

then use a value of  n which is one less than the number of points in x or y: polyfit(x,y,length(x)-1).

(The vectors x and y should have the same length.)

Let’s return to the problem from the homework, interpolating f  

x¡ ¢

1¡  

1x

onto X ¢ ¤

5 ¤

4

5

and onto X 2n ¢5cos

 

nπ¡

10¡

where n¢

01

10. First interpolate onto the points given by

 

X f 

 

X ¡ ¡

:

>> X = -5:5;

>> f = inline(’1./(1 + x.ˆ2)’)

f =

Inline function:

f(x) = 1./(1 + x.ˆ2)

>> p = polyfit(X,f(X),length(X)-1)

The variable p holds the coefficients of the interpolating polynomial. You can evaluate this at the set of 

points in a vector x using the command polyval(p,x):

>> x = linspace(-5,5);

>> y = polyval(p,x);

>> plot(x,y,X,Y,’*’)

You can do the same on the points defined using the cosine. These points are more tightly spaced near the

ends of the interval, and the interpolant over these points is much better behaved. These points are related

to the Chebyshev polynomials which are very useful tools in numerical analysis and approximation theory.

>> X2 = 5*cos([0:10]*pi/10);

>> p2 = polyfit(X2,f(X2),length(X2)-1)

>> plot(x,f(x),x,y2,’--’,X2,f(X2),’*’)

You could fit a quadratic to these points, minimizing the least squares error using:

2

Page 3: matlab_tools.pdf

7/27/2019 matlab_tools.pdf

http://slidepdf.com/reader/full/matlabtoolspdf 3/4

>> pfit = polyfit(X,f(X),2)

pfit =

-0.0230 0.0000 0.4841

>> yfit = polyval(pfit,x);

>> plot(x,f(x),x,yfit,’--’)

The quadratic doesn’t do a great job approximating the function, but you could try different order and could

use this function to fit least squares/best fit lines to any set of data.

Spline interpolation

The polynomial interpolation didn’t do so well on the evenly spaced points. Piecewise polynomial

interpolation can be a powerful tool which avoids the oscillatory (Runge) phenomenon which we saw in

polynomial interpolation over evenly-spaced points. We learned about cubic splines in this class, so let’s

try MATLAB’s built-in spline function. As with the polyfit function, the spline function takes a set of 

data points as arguments. It returns a special MATLAB data structure which holds all of the information

about the spline including the breakpoints and the spline coefficients. You can evaluate the spline at a set of 

locations using the command ppval. MATLAB generally interpolates using the not-a-knot end conditions,

but it can also compute clamped splines. See the documentation on this (or any other function) by typing

help spline (or the name of the other function).

>> pp = spline(X,f(X));

pp =

form: ’pp’

breaks: [-5 -4 -3 -2 -1 0 1 2 3 4 5]

coefs: [10x4 double]

pieces: 10

order: 4

dim: 1

>> y3 = ppval(pp,x);

>> plot(x,f(x),x,y3,X,f(X),’*’)

Here’s what the different interpolants look like — clearly, the cubic spline does the best job of approximating

the function over the whole interval, although interpolation on the cosine points does a reasonable job as

well.

Numerical Integration

You can integrate functions using the MATLAB function quad which performs adaptive integration

using Simpson’s rule. Typing q = quad(f,a,b) will integrate the function f  

from x¢

a to x¢

b. Try

computing 

π

0sin

 

2 dx:

>> f = inline(’sin(x).ˆ2’)

f =

Inline function:

f(x) = sin(x).ˆ2

>> q = quad(f,0,pi)

q =

1.5708

3

Page 4: matlab_tools.pdf

7/27/2019 matlab_tools.pdf

http://slidepdf.com/reader/full/matlabtoolspdf 4/4

In the new MATLAB (version 6.0), there is a new quadl function which uses a high-order scheme to

compute integrals adaptively.

Solving systems of equations

If you want to solve the system of equations Ax¢

b, enter A as a matrix and b as a vector and type

x = A 

b. This solves the system efficiently and will tell you if  A is singular and cannot be inverted. To

compute the LU decomposition of A, type [L, U, P] = lu(A);. For the eigenvalues and eigenvectors of 

A, type [V,D] = eig(A); where V holds the eigenvectors in its columns and D holds the eigenvalues on itsdiagonal.

−5 −4 −3 −2 −1 0 1 2 3 4 5−0.5

0

0.5

1

1.5

2Interpolation of f(x) = 1/(1 + x

2) on evenly−spaced points

x

         f         (      x         )

−5 −4 −3 −2 −1 0 1 2 3 4 5

0

0.2

0.4

0.6

0.8

1Interpolation of f(x) = 1/(1 + x

2) on cosine points

x

         f         (      x         )

functioninterpolantdata points

−5 −4 −3 −2 −1 0 1 2 3 4 50

0.2

0.4

0.6

0.8

1Cubic spline interpolation of f(x) = 1/(1 + x2) on evenly−spaced points

x

         f         (      x         )

Figure 1: Comparison of different interpolation methods in MATLAB.

4