Notes for Math 4445 by S. Adjerid Virginia Polytechnic Institute and State University. (A Rough Draft)

1 Notes for Math 4445 by S. Adjerid Virginia Polytechnic Institute and State University (A Rough Draft) 2 Contents 1 Matlab Tutorial 1.1 Getting ...
Author: Abel Johnson
7 downloads 0 Views 122KB Size
1

Notes for Math 4445 by S. Adjerid Virginia Polytechnic Institute and State University (A Rough Draft)

2

Contents 1 Matlab Tutorial 1.1 Getting started . . . . . . . . . . . . 1.2 Buit-in functions . . . . . . . . . . . 1.3 Plotting curves and surfaces . . . . . 1.4 Matrices . . . . . . . . . . . . . . . . 1.5 Programming in Matlab . . . . . . . 1.6 Solving nonlinear algebraic equations 1.7 Problems . . . . . . . . . . . . . . . .

3

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

5 5 10 10 12 14 17 23

4

CONTENTS

Chapter 1 Matlab Tutorial 1.1

Getting started

We start by defining the arithmetic operations in matlab in the following tables Arithmetic Operations * + \ / ˆ

multiplication addition subtraction left division right division power

At the matlab prompt type

>> format long >> orange = 3 orange= 3 >> orange = 3; >> orange 5

6

CHAPTER 1. MATLAB TUTORIAL orange = 3

>> apple = 13; >> orange + apple ans = 13 >> c = apple*orange; >> c c = 39 >> b = c*orange/5 + apple^3 b = 2.220400000000000e+03

(2.2204 *10^3 )

>> d = sqrt(b) d = 47.12112052997043

One may change the format of the output using the command ’format’ as defined in the following table. format format format format format format format

short long short e long e short g long g rational

5 digits 16 digits 5 digits scientific 16 digits scientific 5 digits 16 digits rational number

Let us change the format to see the effect

1.1. GETTING STARTED >> format >> f = 2/3 f = 0.66666666666667 >> format short >> g = 2/3 g = 0.6667 >> format short e >> 2/3 ans = 6.6667e-01 >> format long e >> 2/3 ans = 6.666666666666666e-01

Vectors in Matlab >>v = [1; 3; -3; 4] v = 1 3 -3 4 >> v = [ 1 3 -3 4 ]

7

8

CHAPTER 1. MATLAB TUTORIAL

v = 1

3

-3

4

>> w = 2*v; >> z = w + v z = 3 9 -9 12 >> z’ (change the orientation of the vector) ans = 3 9 -9 12 >>x = 0:0.2:3; >> length(x) ans = 16 >> x(8:12) ans = 1.4000

1.6000

1.8000

2.0000

2.2000

>> y = cos(x); >> y y = Columns 1 through 7 1.0000

0.9801 0.9211

0.8253

0.6967

0.5403

0.3624

9

1.1. GETTING STARTED

Columns 8 through 14 0.1700 -0.0292 -0.2272

-0.4161 -0.5885 -0.7374 -0.8569

Columns 15 through 16 -0.9422 -0.9900 >> y(1) ( will print y(1)) S

Operations of vectors and scalars if a = [a1 , a2 , · · · an ], b = [a1 , a2 , · · · , an ] , c is a scalar.

a+c a∗c a\c a+b a. ∗ b a./b a. \ b a.ˆb c.ˆb a.ˆc

= = = = = = = = = =

[a1 + c, a2 + c, · · · , an + c] [a1 ∗ c, a2 ∗ c, · · · , an ∗ c] [a1 \ c, a2 \ c, · · · , an \ c] [a1 + b1 , a2 + b2 , · · · , an + c] [a1 ∗ b1 , a2 ∗ b2 , · · · , an ∗ bn ] [a1 /b1 , a2 /b2 , · · · , an /bn ] [b1 \ a1 , b2 \ a2 , · · · , bn \ an ] [ab11 , ab22 , · · · , abnn ] [ca1 , ca2 , · · · , can ] [ac1 , ac2 , · · · , acn ]

>> u = [w,v] (will append the two vectors) >> norm(v,p) ( computes the L^p norm, p>=1)

10

1.2

CHAPTER 1. MATLAB TUTORIAL

Buit-in functions sin cos tan artan acos asin exp log log10 log2 sinh cosh tanh sec abs sign max min

sine function cosine function tangent inverse tangent inverse cosine inverse sine exponential natural logarithm decimal logarithm binary logarithm hyperbolic sine hyperbolic sine hyperbolic sine secant absolute value sign function maximum minimum

These function may accept scalar, vector, and matrix arguments.

1.3

Plotting curves and surfaces

The following table contains some important commands to plot curves and surfaces.

1.3. PLOTTING CURVES AND SURFACES figure(n) clf hold on plot xlabel ylabel zlabel xaxis yaxis zaxis subplot view surf contour meshgrid pcolor

11

create or change figure n clears current figure hold existing plots in a figure plots a curve defines the label for x axis defines the label for y axis defines the label for z axis define range and tics on x axis define range and tics on y axis define range and tics on z axis define and switch subplots change view for surfaces plots surfaces plots contour for surfaces create coordinates for grid points plots solution in a plane

For example the following program will plot the graph of y = cos(2x) + exp(x), 0 ≤ x ≤ 2 in dash-dot line and blue color >> x = 0:0.1:2; >>y = cos(2*x) + exp(x); >>plot(x,y,’-.b’) You may set colors using b: blue, r:red, y:yellow and g:green. The type of lines is set by -:solid, ..:dotted, -.:dash-dot, +:plus symbol: for other symbols and lines types consult the online tutorial. To plot two curves on the same figure use ’hold on’. >> x = 0:0.1:2; >>y = cos(2*x) + exp(x); >>z = tanh(x) ; >>plot(x,y,’-.b’); >>hold on >>plot(x,z,’-r’); Let us plot a 3D graph of z = cos(xy) + cos(x)

12

CHAPTER 1. MATLAB TUTORIAL

>>figure(1) >> x = 0:0.1:2; >> y = 0:0.2:4; >> [X,Y] = meshgrid(x,y); >> Z = cos(X.*Y) + cos(X); >>surf(X,Y,Z); >> View(30,65) >>title(’ 3D Surface’); >>figure(2); >>pcolor(X,Y,Z); >>figure(3) >>contour(X,Y,Z,10); In order to create 4 plots in one figure. use >>subplot(2,2,1) >>subplot(2,2,2) >>subplot(2,2,3) >>subplot(2,2,4)

%(to %(to %(to %(to

plot plot plot plot

in in in in

the the the the

upper-left plot) upper-right plot) lower-left plot) lower-right plot)

On the figure window you may (i) left click on File menu and export your image as eps, tiff, · · · . (ii) left click on theleft arrow and then on the plot and a window will appear where you can ajust the axes marks, labels, color and type of the plot. (iii) left click on A and left click on the plot to add text to your plot

1.4

Matrices

>> A = [ 2 3 ; -7 9 ] A = 2 -7

3 9

>> C = [ 8 9 ; -10 12]

13

1.4. MATRICES

C = 8 -10

9 12

>> B = A + C B = 10 -17

12 21

>> D = A*B D = -31 87 -223 105 >> det(A) ans = 39 >> inv(A) ans = 0.23076923076923 0.17948717948718

-0.07692307692308 0.05128205128205

Matrix functions

14

CHAPTER 1. MATLAB TUTORIAL det(A) A’ eig(A) lu(A) qr(A) A\f norm(A,p) size(A) sparse full(As) hess(A) cond(A,p) luinc(A) trace(A) svd(A) ones(n,m) zeros(n,m) eye(n) spy(A) speye spdiag gmres(A,f) qmr(A,f) cgs(A,f)

determinant transpose of A eigenvalues of A lu factorization QR factorization solve Ax = f norm of A,in Lp , p = 1, 2, inf , or f ro. gives the number of rows and columns define a sparse matrix transform matrix from sparse format to full compute the Hessenberg form p = 1, 2, inf, f ro. computes the condition number incomplete lu factorization trace of A singular value decomposition an n × m matrix containing all ones an n × m matrix containing all zeros an n × n identity matrix shows the sparse structure sparse identity matrix sparse diagonal matrix use gmres to solve Ax=f use qmr to solve Ax=f Preconditioned conjugate gradient

For more help

1.5

Programming in Matlab

Relational Operators < >= == ∼=

less than less or equal greater than greater or equal equal not equal to

1.5. PROGRAMMING IN MATLAB

15

Logical Operators & and | or e not Control Flow One may write a set of instructions and save them in one file with extension .m Example of a script to illustrate the use of if if (a > 2) & a ( a < 11) z = cos(a)^2; else z = exp(a); end Script that use f or x=[2,3,-3,4,-9,0]; S=0; for i=1:length(x) if( x(i)>0) S = S + x(i) end end

A=[2,3,-3;4,-9,0]; S=0; [n,m]=size(A); for i=1:n for j=1:m if( A(i,j)>1) & (A(i,j) 1 epsilon = epsilon/2; end epsilon = 2*epsilon Example: Compute the sum

∞ P n=1

n2 +sin(n) 1+en

%file example.m eps=machinezero; sum =f(1); n=1; while abs(f(n+1)/sum) > 2*eps sum = sum+ f(n+1) n=n+1 end; n sum % file f.m function f=f(n) f=(n^2+sin(n))/(1 + exp(n)); Passing functions as arguments to other functions Consider the file mysum.m which contains the following function

1.6. SOLVING NONLINEAR ALGEBRAIC EQUATIONS

17

function S = mysum(x,y,myfun) S = feval(myfun,x) + feval(myfun,y); you would call it as >> x = 12; >>y=-13.8; >> d = mysum(x,y,’sin’); Timing your code: To time you code or parts of it you may use the cputime command as illustrated in the following example >> t0 = cputime; >> x=12; >> y=13; >> s = mysum(x,y,’sin’); >>t1 = cputime >> cpu_time = t1-t0; One line help may be obtained by typing at the matlab prompt >>help or >> help norm %(to get help on norm) >>help lu % (help on how to use lu function) >>help format %(help on format) You may also check the online manual at http://math.ucsd.edu/~driver/21d-s99/matlab-primer.html

1.6

Solving nonlinear algebraic equations

The bisection method Let f be a continuous function on [a, b] such that f (a)F (b) < 0. Then there exists at least one root x∗ ∈ (a, b) such that f (x∗ ) = 0.

18

CHAPTER 1. MATLAB TUTORIAL

The bisection method consists in computing c = a+b , if the f (a)f (c) < 0 the 2 next interval will be [a, c], otherwise we use the interval [c, b]. We continue this process until we reach an interval whose length and/or |f (c)| is less than a prescribed tolerance. function [a,b]=bisection(a1,b1,fun,eps,nmax) %This function uses the bisection method to approximate %roots of f(x)=0 %input: %[a1,b1] interval that contains a root %fun: the function f %eps: tolerance %nmax: maximum number of iterations allowed %output: [a,b] a final interval containing the root % fp1 = feval(fun,a1); fp2 = feval(fun,b1); if(fp1*fp2 > 0) display(’ This function might not have a root in this interval’); end % iter = 1; while (b1-a1) > eps & (iter o |xn−1 − x∗ |1.6

22

CHAPTER 1. MATLAB TUTORIAL

function [p,iter]=secant(a1,b1,fun,eps,nmax) %This function computes approximation to roots of f(x)=0 %using the secant method %input: %a1,a2 are two intial guesses %fun : function f %eps : tolerance %nmax: maximum number of iterations %output: %p : approximation to the root of f(x)=0 % fp1 = feval(fun,a1); % iter = 1; while abs(b1-a1) > eps & (iter 0 , x0 2 −10 10 . Excute your progam with a

7. Write a program for the iteration xk+1 = |xk+1 −xk | |xk |

=a

< = 2 and print all the that stops when k > 100 or iterations √ xi , i = 0, 1, · · · generated by your program and compare the final result to the exact value 2. Use format long to display your results

References

1. Mastering Matlab, Hanselmann and Littlefield, Prentice Hall. 2. Numerical Methods with Matlab, Gerald Recktenwald, Prentice Hall 3. Matlab Guide, Desmond, Highman and Nichold Highman, Society of Industrial and Applied Mathematics (SIAM).

Suggest Documents