Lecture notes Matlab programming

Introduction to Numerical Methods and Matlab Programming for Engineers how to learn matlab quickly. lecture notes on matlab simulink pdf free download
LottieBarners Profile Pic
Published Date:12-07-2017
Your Website URL(Optional)
Introduction to Numerical Methods andMatlab Programming for Engineers Todd Young and Martin J. Mohlenkamp Department of Mathematics Ohio University Athens, OH 45701 youngtohio.edu May 4, 2017ii c Copyright 2008, 2009, 2011, 2014, 2016, 2017 Todd R. Young and Martin J. Mohlenkamp. Original edition 2004, by Todd R. Young. This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/.Preface These notes were developed by the rst author in the process of teaching a course on applied numerical methods for Civil Engineering majors during 2002-2004 and was modi ed to include Mechanical Engineering in 2005. The materials have been periodically updated since then and underwent a major revision by the second author in 2006-2007. The main goals of these lectures are to introduce concepts of numerical methods and introduce Matlab in an Engineering framework. By this we do not mean that every problem is a \real life" engineering application, but more that the engineering way of thinking is emphasized throughout the discussion. The philosophy of this book was formed over the course of many years. My father was a Civil Engineer and surveyor, and he introduced me to engineering ideas from an early age. At the University of Kentucky I took most of the basic Engineering courses while getting a Bachelor's degree in Mathematics. Immediately afterward I completed a M.S. degree in Engineering Mechanics at Kentucky. While working on my Ph.D. in Mathematics at Georgia Tech I taught all of the introductory math courses for engineers. During my education, I observed that incorporation of computation in coursework had been extremely unfocused and poor. For instance during my college career I had to learn 8 di erent programming and markup languages on 4 di erent platforms plus numerous other software applications. There was almost no technical help provided in the courses and I wasted innumerable hours guring out software on my own. A typical, but useless, inclusion of software has been (and still is in most calculus books) to set up a dicult `applied' problem and then add the line \write a program to solve" or \use a computer algebra system to solve". At Ohio University we have tried to take a much more disciplined and focused approach. The Russ College of Engineering and Technology decided thatMatlab should be the primary computational software for undergraduates. At about the same time members of the Department of Mathematics proposed an 1804 project to bring Matlab into the calculus sequence and provide access to the program at nearly all computers on campus, including in the dorm rooms. The stated goal of this project was to make Matlab the universal language for computation on campus. That project was approved and implemented in the 2001-2002 academic year. In these lecture notes, instruction on usingMatlab is dispersed through the material on numerical methods. In these lectures details about how to use Matlab are detailed (but not verbose) and explicit. To teach programming, students are usually given examples of working programs and are asked to make modi cations. The lectures are designed to be used in a computer classroom, but could be used in a lecture format iiiiv PREFACE with students doing computer exercises afterward. The lectures are divided into four Parts with a summary provided at the end of each Part. Todd Young Dependencies Below we give the dependencies between Lectures. Almost everything depends on Lectures 14, so those links are omitted to reduce clutter. Some lectures, marked with in the table of contents, have not yet been developed. Part II 13 18 16-17 8 9 12 14 15 10 11 Part III 19-20 24 22 25 21 23 28 27 26 Part I 7 Part IV 35 36-37 1-4 5-6 41-42 38-39 Everything in Parts II,III,IV 33 34 29-32Contents Preface iii I Matlab and Solving Equations 1 Lecture 1. Vectors, Functions, and Plots inMatlab 2 Lecture 2. Matlab Programs 6 Lecture 3. Newton's Method and Loops 10 Lecture 4. Controlling Error and Conditional Statements 14 Lecture 5. The Bisection Method and Locating Roots 18 Lecture 6. Secant Methods 22 Lecture 7. Symbolic Computations 25 Review of Part I 29 II Linear Algebra 33 Lecture 8. Matrices and Matrix Operations in Matlab 34 Lecture 9. Introduction to Linear Systems 39 Lecture 10. Some Facts About Linear Systems 43 Lecture 11. Accuracy, Condition Numbers and Pivoting 46 Lecture 12. LU Decomposition 50 Lecture 13. Nonlinear Systems - Newton's Method 53 Lecture 14. Eigenvalues and Eigenvectors 57 Lecture 15. Vibrational Modes and Frequencies 60 Lecture 16. Numerical Methods for Eigenvalues 63 vvi CONTENTS Lecture 17. The QR Method 67 Lecture 18. Iterative solution of linear systems 69 Review of Part II 70 III Functions and Data 73 Lecture 19. Polynomial and Spline Interpolation 74 Lecture 20. Least Squares Fitting: Noisy Data 78 Lecture 21. Integration: Left, Right and Trapezoid Rules 81 Lecture 22. Integration: Midpoint and Simpson's Rules 86 Lecture 23. Plotting Functions of Two Variables 90 Lecture 24. Double Integrals for Rectangles 93 Lecture 25. Double Integrals for Non-rectangles 97 Lecture 26. Gaussian Quadrature 100 Lecture 27. Numerical Di erentiation 101 Lecture 28. The Main Sources of Error 105 Review of Part III 108 IV Di erential Equations 115 Lecture 29. Reduction of Higher Order Equations to Systems 116 Lecture 30. Euler Methods 120 Lecture 31. Higher Order Methods 124 Lecture 32. Multi-step Methods 127 Lecture 33. ODE Boundary Value Problems and Finite Di erences 128 Lecture 34. Finite Di erence Method Nonlinear ODE 132 Lecture 35. Parabolic PDEs - Explicit Method 135 Lecture 36. Solution Instability for the Explicit Method 140CONTENTS vii Lecture 37. Implicit Methods 143 Lecture 38. Insulated Boundary Conditions 147 Lecture 39. Finite Di erence Method for Elliptic PDEs 152 Lecture 40. Convection-Di usion Equations 155 Lecture 41. Finite Elements 156 Lecture 42. Determining Internal Node Values 160 Review of Part IV 164 V Appendices 167 Lecture A. Glossary of Matlab Commands 168viii CONTENTSPart I Matlab and Solving Equations c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017Lecture 1 Vectors, Functions, and Plots in Matlab In these notes will indicate commands to be entered at the Matlab prompt in the command window. You do not type the symbolj. Entering vectors In Matlab, the basic objects are matrices, i.e. arrays of numbers. Vectors can be thought of as special matrices. A row vector is recorded as a 1n matrix and a column vector is recorded as a m 1 matrix. To enter a row vector in Matlab, type the following in the command window: v = 0 1 2 3 and press enter. Matlab will print out the row vector. To enter a column vector type u = 9; 10; 11; 12; 13 You can access an entry in a vector with u(2) and change the value of that entry with u(2)=47 You can extract a slice out of a vector with u(2:4) You can change a row vector into a column vector, and vice versa easily in Matlab using w = v' (This is called transposing the vector and we call ' the transpose operator.) There are also useful shortcuts to make vectors such as 23 x = -1:.1:1 y = linspace(0,1,11) Basic Formatting To make Matlab put fewer blank lines in its output, enter format compact To make Matlab display more digits, enter format long Note that this does not change the number of digits Matlab is using in its calculations; it only changes what is diplayed. Plotting Data 1 Consider the data in Table 1.1. We can enter this data intoMatlab with the following commands entered  T (C ) 5 20 30 50 55  0.08 0.015 0.009 0.006 0.0055 Table 1.1: Viscosity of a liquid as a function of temperature. in the command window: x = 5 20 30 50 55 y = 0.08 0.015 0.009 0.006 0.0055 Entering the name of the variable retrieves its current values. For instance x y We can plot data in the form of vectors using the plot command: plot(x,y) This will produce a graph with the data points connected by lines. If you would prefer that the data points be represented by symbols you can do so. For instance plot(x,y,'') plot(x,y,'o') plot(x,y,'.') 1 Adapted from Ayyup &McCuen 1996, p.174.4 LECTURE 1. VECTORS, FUNCTIONS, AND PLOTS IN MATLAB Data as a Representation of a Function A major theme in this course is that often we are interested in a certain function y = f(x), but the only information we have about this function is a discrete set of dataf(x ;y )g. Plotting the data, as we did i i above, can be thought of envisioning the function using just the data. We will nd later that we can also do other things with the function, like di erentiating and integrating, just using the available data. Numerical methods, the topic of this course, means doing mathematics by computer. Since a computer can only store a nite amount of information, we will almost always be working with a nite, discrete set of values of the function (data), rather than a formula for the function. Built-in Functions If we wish to deal with formulas for functions, Matlab contains a number of built-in functions, including all the usual functions, such as sin( ), exp( ), etc.. The meaning of most of these is clear. The dependent variable (input) always goes in parentheses in Matlab. For instance sin(pi) should return the value of sin, which is of course 0 and exp(0) 0 will return e which is 1. More importantly, the built-in functions can operate not only on single numbers but on vectors. For example x = linspace(0,2pi,40) y = sin(x) plot(x,y) will return a plot of sinx on the interval 0; 2 Some of the built-in functions in Matlab include: cos( ), tan( ), sinh( ), cosh( ), log( ) (natural logarithm), log10( ) (log base 10), asin( ) (inverse sine), acos( ), atan( ). To nd out more about a function, use the help command; try help plot User-De ned Anonymous Functions If we wish to deal with a function that is a combination of the built-in functions, Matlab has a couple of ways for the user to de ne functions. One that we will use a lot is the anonymous function, which is a way to de ne a function in the command window. The following is a typical anonymous function: f = (x) 2x.2 - 3x + 1 2 This produces the function f(x) = 2x 3x + 1. To obtain a single value of this function enter y = f(2.23572)5 Just as for built-in functions, the function f as we de ned it can operate not only on single numbers but on vectors. Try the following: x = -2:.2:2 y = f(x) This is an example of vectorization, i.e. putting several numbers into a vector and treating the vector all at once, rather than one component at a time, and is one of the strengths of Matlab. The reason f(x) works 2 whenx is a vector is because we representedx by x.2. The . turns the exponent operator into entry-wise 2 2 2 exponentiation, so that -2 -1.8 -1.6.2 means (2) ; (1:8) ; (1:6) and yields 4 3.24 2.56. In contrast, -2 -1.8 -1.62 means the matrix product 2;1:8;1:62;1:8;1:6 and yields only an error. The . is needed in ., ., and ./. It is not needed when you or / by a scalar or for +. The results can be plotted using the plot command, just as for data: plot(x,y) Notice that before plotting the function, we in e ect converted it into data. Plotting on any machine always requires this step. Exercises 1.1 Find a table of data in an engineering or science textbook or website. Input it as vectors and plot it. Use the insert icon to label the axes and add a title to your graph. Turn in the graph. Indicate what the data is and properly reference where it came from. 1.2 Find a function formula in an engineering or science textbook or website. Make an anonymous function that produces that function. Plot it on a physically relevant domain. Label the axes and add a title to your graph. Turn in the graph and write on the page the Matlab command for the anonymous function. Indicate what the function means and properly reference where it came from.Lecture 2 Matlab Programs InMatlab, programs may be written and saved in les with a sux .m called M- les. There are two types of M- le programs: functions and scripts. Function Programs Begin by clicking on the new document icon in the top left of the Matlab window (it looks like an empty sheet of paper). In the document window type the following: function y = myfunc(x) y = 2x.2 - 3x + 1; end Save this le as: myfunc.m in your working directory. This le can now be used in the command window just like any prede ned Matlab function; in the command window enter: x = -2:.1:2; % Produces a vector of x values y = myfunc(x); % Produces a vector of y values plot(x,y) Note that the fact we used x and y in both the function program and in the command window was just a coincidence. In fact, it is the name of the le myfunc.m that actually mattered, not what anything in it was called. We could just as well have made the function function nonsense = yourfunc(inputvector) nonsense = 2inputvector.2 - 3inputvector + 1; end Look back at the program. All function programs are like this one, the essential elements are:  Begin with the word function.  There is an input and an output.  The output, name of the function and the input must appear in the rst line.  The body of the program must assign a value to the output variable(s). 67  The program cannot access variables in the current workspace unless they are input.  Internal variables inside a function do not appear in the current workspace. Functions can have multiple inputs, which are separated by commas. For example: function y = myfunc2d(x,p) y = 2x.p - 3x + 1; end Functions can have multiple outputs, which are collected into a vector. Open a new document and type: function x2 x3 x4 = mypowers(x) x2 = x.2; x3 = x.3; x4 = x.4; end Save this le as mypowers.m. In the command window, we can use the results of the program to make graphs: x = -1:.1:1 x2 x3 x4 = mypowers(x); plot(x,x,'black',x,x2,'blue',x,x3,'green',x,x4,'red') Printing, Returning, Capturing, and Printing Try the following: myfunc(3) ans2 Although myfunc returned a value, we did not capture. By default Matlab captured it as ans so we can use it in our next computation. However, Matlab always uses ans (for answer), so the result is likely to get overwritten. Then try: z = 0 z = myfunc(2) z2 myfunc returned a value that it internally called y and we captured the result in z. We can now use z for other calculations. Now make a program function myfuncnoreturn(x) y = 2x.2 - 3x + 1 end8 LECTURE 2. MATLAB PROGRAMS and try: myfuncnoreturn(4) ans2 y2 Although the value of y was printed within the function, it was not returned, so neither the value of y nor the value of ans was changed. Thus we cannot use the result from the function. In general, the best way to use a function is to capture the result it returns and then use or print this result. Printing within functions is bad form; however, for understanding what is happening within a function it is useful to print, so many functions in this book do print. Script Programs Matlab uses a second type of program that di ers from a function program in several ways, namely:  There are no inputs and outputs.  A script program may use, create and change variables in the current workspace (the variables used by the command window). Below is a script program that accomplishes the same thing as the function program plus the commands in the previous section: x2 = x.2; x3 = x.3; x4 = x.4; plot(x,x,'black',x,x2,'blue',x,x3,'green',x,x4,'red') Type this program into a new document and save it as mygraphs.m. In the command window enter: x = -1:.1:1; mygraphs Note that the program used the variable x in its calculations, even though x was de ned in the command window, not in the program. Many people use script programs for routine calculations that would require typing more than one command in the command window. They do this because correcting mistakes is easier in a program than in the command window. Program Comments For programs that have more than a couple of lines it is important to include comments. Comments allow other people to know what your program does and they also remind yourself what your program does if you set it aside and come back to it later. It is best to include comments not only at the top of a program, but also with each section. In Matlab anything that comes in a line after a % is a comment.9 For a function program, the comments should at least give the purpose, inputs, and outputs. A properly commented version of the function with which we started this section is: function y = myfunc(x) % Computes the function 2x2 -3x +1 % Input: x a number or vector; % for a vector the computation is elementwise % Output: y a number or vector of the same size as x y = 2x.2 - 3x + 1; end For a script program it is often helpful to include the name of the program at the beginning. For example: % mygraphs % plots the graphs of x, x2, x3, and x4 % on the interval -1,1 % fix the domain and evaluation points x = -1:.1:1; % calculate powers % x1 is just x x2 = x.2; x3 = x.3; x4 = x.4; % plot each of the graphs plot(x,x,'+-',x,x2,'x-',x,x3,'o-',x,x4,'') The Matlab command help prints the rst block of comments from a le. If we save the above as mygraphs.m and then do help mygraphs it will print into the command window: mygraphs plots the graphs of x, x2, x3, and x4 on the interval -1,1 Exercises 2 2 x 2.1 Write a well-commented function program for the functionx e , using entry-wise operations (such x as . and .). To get e use exp(x). Plot the function on 5; 5 using enough points to make the graph smooth. Turn in printouts of the program and the graph. 2.2 Write a well-commented script program that graphs the functions sinx, sin 2x, sin 3x, sin 4x, sin 5x and sin 6x on the interval 0; 2 on one plot. ( is pi in Matlab.) Use a suciently small step size to make all the graphs smooth. Turn in the program and the graph.Lecture 3 Newton's Method and Loops Solving equations numerically For the next few lectures we will focus on the problem of solving an equation: f(x) = 0: (3.1) As you learned in calculus, the nal step in many optimization problems is to solve an equation of this form where f is the derivative of a function, F , that you want to maximize or minimize. In real engineering problems the functions, f, you wish to nd roots for can come from a large variety of sources, including formulas, solutions of di erential equations, experiments, or simulations. Newton iterations  We will denote an actual solution of equation (3.1) by x . There are three methods which you may have discussed in Calculus: the bisection method, the secant method and Newton's method. All three depend on  beginning close (in some sense) to an actual solution x . Recall Newton's method. You should know that the basis for Newton's method is approximation of a function by its linearization at a point, i.e. 0 f(x)f(x ) +f (x )(xx ): (3.2) 0 0 0 Since we wish to nd x so that f(x) = 0, set the left hand side (f(x)) of this approximation equal to 0 and solve for x to obtain: f(x ) 0 xx : (3.3) 0 0 f (x ) 0  We begin the method with the initial guessx , which we hope is fairly close tox . Then we de ne a sequence 0 of pointsfx ;x ;x ;x ;:::g from the formula: 0 1 2 3 f(x ) i x =x ; (3.4) i+1 i 0 f (x ) i   which comes from (3.3). If f(x) is reasonably well-behaved near x and x is close enough to x , then it is 0  a fact that the sequence will converge to x and will do it very quickly. The loop: for ... end In order to do Newton's method, we need to repeat the calculation in (3.4) a number of times. This is accomplished in a program using a loop, which means a section of a program which is repeated. The 1011 simplest way to accomplish this is to count the number of times through. In Matlab, a for ... end statement makes a loop as in the following simple function program: function S = mysum(n) % Gives the sum of the first n integers % Input: n % Output: the sum S = 0; % start at zero % The loop: for i = 1:n % do n times S = S + i; % add the current integer end % end of the loop end Call this function in the command window as: mysum(100) The result will be the sum of the rst 100 integers. All for ... end loops have the same format, it begins with for, followed by an index (i) and a range of numbers (1:n). Then come the commands that are to be repeated. Last comes the end command. Loops are one of the main ways that computers are made to do calculations that humans cannot. Any calculation that involves a repeated process is easily done by a loop. Now let's do a program that does n steps (iterations) of Newton's method. We will need to input the function, its derivative, the initial guess, and the number of steps. The output will be the nal value of x, i.e.x . If we are only interested in the nal approximation, not the intermediate steps, which is usually the n case in the real world, then we can use a single variable x in the program and change it at each step: function x = mynewton(f,f1,x0,n) % Solves f(x) = 0 by doing n steps of Newton's method starting at x0. % Inputs: f the function % f1 it's derivative % x0 starting guess, a number % n the number of steps to do % Output: x the approximate solution x = x0; % set x equal to the initial guess x0 for i = 1:n % Do n times x = x - f(x)/f1(x) % Newton's formula, prints x too end end In the command window set to print more digits via format long and to not print blank lines via format compact12 LECTURE 3. NEWTON'S METHOD AND LOOPS 3 Then de ne a function: f(x) =x 5 i.e. f = (x) x3 - 5 and de ne f1 to be its derivative, i.e. f1 = (x) 3x2 Then run mynewton on this function. By trial and error, what is the lowest value of n for which the program p 3 converges (stops changing). By simple algebra, the true root of this function is 5. How close is the program's answer to the true value? Convergence 0   Newton's method converges rapidly when f (x ) is nonzero and nite, andx is close enough tox that the 0 linear approximation (3.2) is valid. Let us take a look at what can go wrong. 1=3  0  For f(x) =x we have x = 0 but f (x ) =1. If you try f = (x) x(1/3) f1 = (x) (1/3)x(-2/3) x = mynewton(f,f1,0.1,10) then x explodes. 2  0  For f(x) =x we have x = 0 but f (x ) = 0. If you try f = (x) x2 f1 = (x) 2x x = mynewton(f,f1,1,10) then x does converge to 0, but not that rapidly.  If x is not close enough to x that the linear approximation (3.2) is valid, then the iteration (3.4) gives 0 some x that may or may not be any better than x . If we keep iterating, then either 1 0   x will eventually get close to x and the method will then converge (rapidly), or n   the iterations will not approach x .

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.