Introduction to Programming with Matlab. Jim Dove

Size: px
Start display at page:

Download "Introduction to Programming with Matlab. Jim Dove"

Transcription

1 Introduction to Programming with Matlab Jim Dove Spring Semester, 2005

2 Chapter 1 INTRODUCTION 1.1 The Need for Computers Statistical physics or N-body simulations not possible Monte-Carlo Simulations Many equations simply do not have an analytical solution. Fluid dynamics essentially impossible analytically when one wants the solution as a function of time over evaluated over millions of spatial points. For many complicated systems, more information can be drawn from graphical solutions of the equations. 1.2 Different Computer Languages: Which one is best? There is no such thing as a best language. It depends on the situation. Most C users will agree that C (or C++) is much sleeker than FORTRAN; however, must programmers in physics and astronomy use FORTRAN since their mentors used it and/or they were forced to modify a pre-existing FORTRAN code. Mathematica and other ematical systems have proven very useful for some, but others find it too hard to modify pre-existing subroutines. Spreadsheets are useful for some purposes, but are not complex enough for many sophisticated mathematical operations. MATLAB and IDL are similar to FORTRAN, but has the added bonus that the plotting software is built in, removing the need for input/output manipulations. These languages also have very nice matrix routines. 1

3 CHAPTER 1. INTRODUCTION Basic Structure of Programs Most algorithms that are structured in a top-down design are more elegant and more clear. By topdown, we mean breaking up the original problem into several basic steps, with each step also being broken down into simpler steps. The bottom end, therefore, should consist of the final calculations (usually simple subroutines and/or functions), whereas the uppermost level, which I call the driver or main program, consists of setting up parameters, calling the subroutines/functions, and plotting or outputting the results. A lot of work should be spent on the algorithm of the code. A clear outline of the code, showing the organization of the tasks, should always be done prior to any programming. Your codes should be clear enough such that anyone (with knowledge of the language) can understand the flow. Lots of comments within the code, describing what is occurring or the tasks of the subroutines, makes the code infinitely more understandable. Basic elements of a code: 1. variable declarations, common blocks, parameter settings 2. initial setup of problem: input from the user. 3. computation, with calls to subroutines. 4. output of answer (usually a file printing the values of arrays, to be read by a plotting routine and/or plots) 1.4 Introduction to Matlab When you start up Matlab, you will see a command window. Here there is a command line, a workspace/directory interface, and a command history. the command line is useful for doing simple, short tasks such as plotting a function or doing a symbolic integral. However, for this class, we will be writing programs (m-files). These programs are written using either the built-in Matlab editor (which comes up automatically if you open a file or start a new m-file using the file menu in the command window [upper left]). This editor is convenient as it auto-indents within do loops or if/then conditionals, shows program line numbers (very useful for debugging), and color codes known Matlab commands (a good way to know you have the correct command). After writing a file, you do a save-as and give it a name, and a.m suffix will automatically be appended. Any m-file (with a.m suffix) that is in a directory defined in Matlabs search path will automatically be found and run when the name of the file (excluding the.m suffix) is typed in the executable command line. The search path can be viewed and edited by clicking on set-path in the File menu of the command window. I recommend making some subdirectores such as.../matlab/classical/hw1progs/ and then adding these to your search path.

4 CHAPTER 1. INTRODUCTION Components of a Program There are two types of m-files used for Matlab programming: Scripts (what I call the main program or driver) - These do not accept input arguments, nor do they return output arguments to other programs. Functions (which can also serve as subroutines) - Functions are called by the scripts, typically with input arguments. They do computations and then return one or more arguments. The name of the m-file and the name of the function (defined on the first line of the file) need to be the same. Here is an example of a simple program: % simple1- Driver program in which the user gives the vvalue of x % and the program computes the function func1(x). % Uses func1.m x = input( Enter the value of x: ); f = func1(x) fprintf( function = %g \n,f)... function output = func1(x) % program calculates the value of the polynomial % using the value x output = 2*x^2 + 3*x^3 + sin(x) ; return ;... The... simply show you where the m-file ends (they are not part of the code). A few comments: The name of the function m-file is func1. If this function were to return more than one argument, the first line would have a form

5 CHAPTER 1. INTRODUCTION 4 [output1 output2] = func1(x) and func1 would be called by [f1 f2] = func1(x) Here, f1 would equal output1, and f2 would equal output2. All function programs must terminate with the return command. the semicolons used at the end of the lines suppresses output while the program is running (default is to output the values of all computations). Unlike fortran and many other languages, the driver program does not need a line stating its program name, nor does it need an end command at the end of the program. Percentage signs are used for comments (the compiler ignores them). It is a good idea to describe the use of all programs, program dependencies, and for more complicated programs the meaning of all input and output variables. If you type help filename (where filename is the name of any mfile), you will see all of the comments at the beginning of the file (or immediately after the function declaration for function programs) up until the first blank row or first executable command. The fprintf command is the cleanest way to print output to the screen. String text is in between the apostrophes, except that the %g wildcards tell the compiler to insert the value of the variable (given after the comma) in its place. The number of variables, separated by commas, must be equal to the number of %g wildcards used in the string text. The slash-n flag tells it to start a new line. the input command causes matlab to wait for you to enter in a number or character, and assigns this entry to the variable x. At this stage it would be a good idea to click on the full product family help button in the help menu. Click on the Getting Started with Matlab tutorial. The most important topics you should learn and play around with are: the colon operator arrays (read carefully the More about Matrices and Arrays/Arrays link) Graphics Programming (especially flow control [if, while, for case, etc]) Scripts and Functions (especially global variables, the eval function, preallocation, and function handles)

6 Chapter 2 PLOTS, ROOTS, & INTEGRATION 2.1 Graphics One of the basic operations is evaluating and plotting a function. Using MATLAB, the simplest example is plotting a function that is already compiled. ; this procedure plots a function % set up array for free variable npts = 100 ; xmin = input( enter xmin: ); xmax = input( enter xmax: ); dx = (xmax-xmin)/(npts-1); % set up x array (containing npts), going from xmin to xmax. x = xmin:dx:xmax func = exp(-x) plot(x,func) end Notice that func is now an array with the same dimension as x(func(i) = exp[ x(i)]) We can make the plot look prettier by labeling the axis. plot (x,func) title( Graph of the Sink function ) xlabel( {\it x} ) ylabel( {\it sin(x)/x} ) 5

7 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 6 If you want to plot more than one function on a single plot: func1 = exp(-x) func2 = exp(-2x) plot(x,func1,x,func2) legend( exp(-x), exp(-2x) ) A predefined list of colors allows for discrimination between data sets. The legend command gives a legend (showing the color of the plot and the function) in the upper right-hand corner of the plot. If you want to control the color, linestyle, and marker (for individual data points), use plot(x,y, color-linestyle-marker ), where color-linestyle-marker is a string containing 1-3 characters: Color strings are c,m,y,r,g,b,w, and k, corresponding to cyan, magenta, yellow, red, green, blue, white, and black. Linestyle strings are - (solid), (dashed), : (doted), -. (dash-dot) and none (no line). The marker types are +, o,, and x. Filled marker types are s (filled square), d (diamond), v (down triangle), > (right triangle), < (left triangle), p (pentagram), and h (hexagram). For example, plot(x,y, r-,x,z, b:s ) will plot a red solid line and overplot z(x) using a blue dotted line with square data points. will plot a red solid line with individual data points shown as solid squares. 2.2 Finding Roots Very often one is faced with an equation in which the root can not be found analytically. For example, there is not analytical solution to cos(x) = x. (2.1) Therefore, we need a way to find the roots numerically. It is customary to lump the whole equation such that f(x) = cos(x) x = 0. (2.2) Therefore, we need to find for the roots of f(x). First step might be to plot the function and visualize about where it crosses Bisection Method Once the region where the root exists is determined, the simplest method is to zoom in, dividing the region by two and continue to determine in which half the root exists. For example:

8 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 7 f(x) 0 x % bisectdriver % this program is the driver for finding the root of a function % via the bisection method. It, along with supplying the function routine % are the only parts of code that need to be altered. % % uses bisect.m % fname = name of function % set up initial range in which the root exists. xmin = input( enter xmin: ) ; xmax = input( enter xmax: ) ; % Name the function we are finding the root fname = f1 ; %set the tolorance desired tol = 1.e-3 ; % call the subroutine bisect and get the root (xroot). xroot= bisect(fname,xmin,xmax,tol) ; fprintf( the root is x = %g \n,xroot)... function xroot = bisect(function_name,xmin,xmax,tol) % This procedure finds the root of the function defined by % the function_name string, given that the root exists

9 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 8 % in the range between xmin and xmax. The procedure % will output the root xroot within the tolorance, % where abs(xroot) < tol. xl = xmin ; xr = xmax ; % confirm that the function changes signs within this range: fleft = feval(function_name,xl) ; fright= feval(function_name,xr) ; if fleft*fright >= 0. then fprintf( no root within this range ) return end xmid = (xr + xl)/2.0 ; fmid = feval(function_name,xmid) ; error = abs(fmid) ; % begin bisecting until the midpoint is the root (within tolorance) while error > tol % determine which half the root exists if fleft*fmid < 0. xr = xmid ; else xl = xmid ; end xmid = (xr + xl)/2. ; fleft = feval(function_name,xl) ; fright= feval(function_name,xr) ; fmid = feval(function_name,xmid) ; error = abs(fmid) ; fprintf( xtry and error: %g %g \n,xmid,error) end xroot = xmid ; return ;... function output = f1(x) output = cos(x) - x ;

10 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 9 return ; Setting xmin = 0 and xmax = 5.0 produced the following output: xtry and error: xtry and error: xtry and error: xtry and error: xtry and error: xtry and error: xtry and error: xtry and error: xtry and error: xtry and error: xtry and error: the root is x = The nice thing about this method is that it will always work! Unfortunately, sometimes it takes a long time. Matlab has a built-in root-finder, called fzero. You can enter type fzero in the command line to see this program (it is quite more complicated than the program used above). Entering help fzero will give you the syntax Newton-Raphson Method The main idea behind the Newton-Raphson method is to use the derivative of the function to help one determine what the next guess should be. Remember that the Taylor expansion of a function is f(x) f(a) + f (a)(x a) + (2.3) Therefore, looking for x 0 such that f(x 0 ) = 0, we get x 0 a f(a) f (a). (2.4) Pictorally, it is the higher order terms in the Taylor expansion that cause the function s derivative not to point exactly to its root. This method is much faster than the bisection method! Note that this method has problems for any function in which f (x) = 0 or. Also, for crazy functions, the derivative might constantly cause the guess to overshoot to either side. For these reasons, it is best to plot the function first to see its form.

11 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION Integration Numerical integration is also called quadrature. Quadrature is the simplest case of solving the richer field of numerical integration of differential equations. The evaluation of the integral is identical to solving for y(b), where and y(a) = 0. I = dy dx b a f(x)dx (2.5) = f(x), (2.6) We will cover the more versatile (and complex) techniques of solving differential equations later, and discuss the simpler problem of quadrature methods. All quadrature methods boil down to adding up the value of the integrand at a sequence of locations within the range of integration. Different methods approximate the integral more accurately (for a given number of steps) than others Trapezoidal Rule and Simpson s Rule This method is the simplest, and most historically important, but not very accurate. It does serve well to help conceptualize numerical integration. f(x) a x x x x 1 3 n b Consider a function f(x) that is to be integrated from a to b.

12 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 11 A first guess is given by cutting the function up into N pieces, equally spaced, and summing the area of each rectangle (with height f(x i ) and width (b a)/n), where h is the width of each segment. N I f(x i )h, (2.7) i=0 The error is due to the function changing within the interval, and therefore the more segments used, the more accurate the approximation. However, there are methods (fitting polynomials to the function) that reduce the error for a given N. Trapezoidal Rule Consider the approximation of the area of one segment, between x 1 and x 2. Rather than using f(x 2 ) as the height of the rectangle, one can use the median height, [f(x 2 ) + f(x 1 )]/2. Therefore, where f i = f(x i ). x 2 x 1 f(x)dx = [ f1 2 + f ] 2 h, (2.8) 2 This is in fact the area of a trapezoid. In fact, if the function were linear between x 1 and x 2, this approximation would be precise. One could have derived this equation by assuming the function to be linear. The Trapezoid Rule can be applied to each segment, and then summed together, or x N x 0 = h 2 (f 0 + f 1 ) + h 2 (f 1 + f 2 ) + h 2 (f 2 + f 3 ) + + h 2 (f N + f N 1 ), (2.9) I = h( f f 1 + f f N 1 + f N ). (2.10) 2 Here is a very basic program using the Trapazoid rule to integrate a function. % program trapzd_driver % this is the main program that uses trapazoid rule % to integrate the function f1 from a to b. a = input( enter xmin: ) ; b = input( enter xmax: ) ; N = input( enter N, where number of points= 2^N + 1: )

13 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 12 f1 = func ; xint = trapzd(f1,a,b,n) ; fprintf( the answer is %g \n,xint) ;...function result=trapzd(function_name,xmin,xmax,n) % this function uses the trapezoid rule to evaluate % the integral of the function function_name from % xmin to xmax using 2^N + 1 points (2^N - 1 interior points) f1 = feval(function_name,xmin) ; f2 = feval(function_name,xmax) ; npts = 2^N + 1 ; % Now look at internal points deltax = (xmax-xmin)/npts ; % this is the spacing between points x = xmin + deltax ; sum = 0.0 ; while x < xmax fx = feval(function_name,x) ; sum = sum + fx ; x = x + deltax ; end result = deltax*(f1/2. + f2/2 + sum); return ;... function output = func(x) output = x^(10); return ;... In practice, it is not clear what one should set N to a priori. Therefore, a routine is needed to continue to decrease the stepsize until a specific tolerance is reached. One could compare the output

14 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 13 while incrementing N and stopping when the relative difference drops below a set tolerance. In doing this, it is customary to use previous calls to trapzd, while only looking at the new internal points (when increasing N) in determining the new integral. This speeds up the routine. Simpson s Rule In the trapezoidal approximation the integral is estimated by assuming the function is a straight line between the endpoints. A more accurate method is to use a quadratic (parabolic) interpolation procedure through adjacent triplets of points. For example, the eqaution of the second-order polynomial that passes through the points (x 0, y 0 ), (x 1, y 1 ), and (x 2, y 2 ) can be written as (x x 1 )(x x 2 ) y(x) = y 0 (x 0 x 1 )(x 0 x 2 ) + y (x x 0 )(x x 2 ) 1 (x 1 x 0 )(x 1 x 2 ) + y (x x 0 )(x x 1 ) 2 (x 2 x 1 )(x 2 x 1 ). The integral (after some tedious algebra) becomes x2 x 0 y(x) dx = 1 3 (y 0 + 4y 1 + y 2 ) x, where x = x 2 x 1 = x 1 x 0. This is Simpson s Rule. If the region is cut up into n bins (with n + 1 points including the end points), then the total area under all the parabolic segments is where h = (x n x 0 )/n. F n = h 3 [f(x 0) + 4f(x 1 ) + 2f(x 2 ) + 4f(x 3 ) f(x n 1 ) + f(x n )], One could continue to increase the order of the polynomial and derive more and more complicated formulae, but in practice these aren t used, as it is easier to simply reduce the interval of the integration. There are much more sophisticated methods of integration (particulary, a method called Romberg Integration), but this will get you started. Matlab has nifty built-in program quadrature (numerical integration) functions. One nice one is quad, which uses adaptive stepsizes and Simpson s rule. Here is an example of its use: function f = hcurve(t) f = sqrt(cos(2*t).^2 + sin(t).^2 + 1) return ;... integral = quad(@hcurve,0,3*pi)

15 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 14 This evaluates the integral of the function hcurve from 0 to 3π. Notice the dots in the function hcurve (prior to the carots). These dots are array operators that force each element of the array t to be operated one at a time (so the whole array isn t being squared!). See the documention page for more information on quad (and other quadrature routines) Improper Integrals An improper integral is one with any of the following properties: The integrand approaches ± as x approaches the limit of integration (i.e., singularity). One or both of the limits of integrations is ±infty. The integrand can not be evaluated right at the limit(s) of integration (even though the function may converge). One method of resolving improper integrals is to use a variable substitution. One common trick is using the identity b a f(x)dx = 1/a 1/b f(1/t) 1 t2dt, (2.11) where ab > 0 (to avoid singularity at t = 0). This is particularly useful if the original limit of integration included ±. Also notice that it is possible to call a numerical integrator as before, but using a new function gfunc(x) = func(1/x) /x 2, as well as passing the new limits of integration, 1/a and 1/b. Note that functions in which f (a) =, where a is a limit of integration, are also problematic, as all the methods we are using so far rely on Taylor expansion, with high-order terms being negligible. Again, variable substitution is recommended to force the spacing of the intervals to be small in the area where the derivitave becomes very steep Multidimensional Integration For multidimensional integrals, you must specify the region of space to be integrated over rather than simply the boundary conditions. The easiest case is rectangular regions of integration. For example, Can be broken down to I = x 2 x 1 I = y 2 y 1 f(x, y)dxdy (2.12) x 2 x 1 g(x)dx, (2.13)

16 CHAPTER 2. PLOTS, ROOTS, & INTEGRATION 15 where g(x) = y 2 y 1 f(x, y)dy. Typically, the boundaries of the inner integral depend on the variable of the outer integral. For example, if one wants to calculate the potential due to a charged disk, where x 2 + y 2 a 2, then V (x, y, z) = a a a 2 x 2 a 2 x 2 σdy dx. (2.14) (x x ) 2 + (y y ) 2 + z 2 Each integral can be treated as before, but note that the function of the outer integral, an integral itself, can be quite time consuming to evaluate. For integrals having more than 3 dimensions, it becomes too time consuming to calculate integrals using polynomial approximations to the integrand. One solution is to use a Monte Carlo technique. Briefly, this technique involves generating random numbers, and using the fraction of times these numbers are inside the integral to calculate its value. You can learn about this technique if you take Computational Physics.

17 Chapter 3 ORDINARY DIFFERENTIAL EQUATIONS 3.1 Initial Boundary Conditions First Order Differential Equations Consider the equation dy = f(x, y). (3.1) dx If f(x, y) were solely a function of x then, from a Taylor expansion, which means y(x) = y(x 0 ) + (x x 0 )y (x 0 ) + (x x 0) 2 y (x) +, (3.2) 2 y(x) y(x 0 ) + (x x 0 )f(x 0 ). (3.3) In subscript notation, where y n is y(x n ), and y n 1 is known, y n y n 1 +(x n x n 1 )f(x n 1 ). Starting with initial conditions y 0 = f(x 0 ), y(x n ) can be determined iteratively by stepping forward step by step. Note that solving for y(x f ) would be equivalent to using rectangles to numerically integrate f(x) from x 0 to x f. A more accurate approach would be to use Simpson s rule or Romberg integration to integrate f(x) from x 0 to x f. Now suppose f(x, y) depends both on x and y Euler s Method The simplest approach is to simply use both the previous values of y and x when calculating y = f: y(x) y(x 0 ) + (x x 0 )y (x 0 ) = y(x 0 ) + (x x 0 )f(x 0, y(x 0 )). (3.4) 16

18 CHAPTER 3. ORDINARY DIFFERENTIAL EQUATIONS 17 In subscript notation, y n = y n 1 + hf(x n 1, y n 1 ), where h = x n x n 1. Euler s method is more historically important than being useful, as the errors tend to be large for all but the simplest functions (even if h is really small). As usual, a much better approximation is obtained if symmetry is used (information of the derivative at both endpoints). For example, one can use the mean derivative (evaluated at both endpoints) in estimating y(x), y n = y 0 + hf avg, (3.5) where f avg = (f(x n 1, y n 1 ) + f(x n, ynest))/2, and ynest = y n 1 + hf(x n 1, y n 1 ) [ynest is simply determined using Euler s method]. This is termed the Improved Euler Method. Another method is the Modified Euler method, where the derivative is evaluated at the midpoint of the step : (f(x n 1 + h/2, y n 1 + hf(x n 1, y n 1 )/2)). These methods can be derived by noting the exact identity y(x) = y(x 0 + h) = y(x 0 ) + x x 0 f(x, y[x ])dx. (3.6) since y[x ] cannot be known a priori, the integral is estimated in some way. For example, using the midpoint rule for estimating the integral, This is the modified Euler Method. y(x) y(x 0 ) + hf(x 0 + h/2, y(x 0 ) + hf(x 0, y 0 )/2). (3.7) Runge-Kutta Methods The Improved and Modified Euler Methods are actually simple examples of the Runge-Kutta method, where the derivative (y (x, y) = f(x, y)) is approximated by evaluating f at different values of x and y (this is different than Taylor series, where different derivatives are evaluated at the same point). In fact, these methods are 2nd order Runge-Kutta methods. The different steps are used to test the water before taking the plunge. Different weights can be assigned to the information (slope at a particular point) from each trial step, and all the information can be added up in a way to reduce the leading error term. The two-variable Taylor expansion is given by f(x + h, y + g) = i=0 ( 1 h d i! dx dy) + g d i f(x, y), where all derivatives are evaluated at (x, y). Runge-Kutta methods can also be derived by assuming a form for y(x) in terms of unknown coefficients (and f and h) and solving for these coefficients such that the form is equal to the Taylor expansion. A second order Runge-Kutta scheme assumes a form

19 CHAPTER 3. ORDINARY DIFFERENTIAL EQUATIONS 18 of y(x 0 + h) = y 0 + w 1 hf(x 0, y 0 ) + w 2 hf(x + αh, y 0 + βhf(x 0, y 0 )). Here, w 1, w 2, α, and β are solved such that this expression matches the Taylor expansion for terms up to i = 2. One workhorse is the 4th Order Runge-Kutta method (meaning the leading error term is of order O(h 5 ). The derivation is very lengthy, so I ll just give the answer: f 0 = f(x 0, y 0 ) (3.8) f 1 = f(x 0 + h/2, y 0 + hf 0 /2) (3.9) f 2 = f(x 0 + h/2, y 0 + hf 1 /2) (3.10) f 3 = f(x 0 + h, y 0 + hf 2 ) (3.11) ( f0 y(x 0 + h) = y(x 0 ) + h 6 + f f f ) 3. (3.12) 3 Implementing this method requires a step size to be given. Here is a straight forward example: % runga4_driver % this is the most straightforward driver of the Runge-Kutta method, % solving the differential equation y (x,y) = f(x,y) from x = a to x = b % using the initial conditions y(a) and y (a). y (x,y) is given % by the function deriv_name. derive_name = derivs ; % Set up initial conditions ystart=input( enter y(xstart) ) ; xstart = 0.0 ; xend = 5.0 ; % determine number of steps to make for the integral npts = 500 ; % set an array that holds the values of y(x) (y(i) = y(x_i)) yarray = zeros(npts) ; h = (xend-xstart)/(npts-1) ; xarray = xstart:h:xend ; % Now determine yarray (y(x)) x = xstart ;

20 CHAPTER 3. ORDINARY DIFFERENTIAL EQUATIONS 19 y = ystart ; yarray(1) = ystart ; for i=2:npts dydx = feval(derive_name,x,y) ; y = runga4(y,dydx,x,h,derive_name) ; yarray(i) = y ; x = x + h ; end plot(xarray,yarray)... function yout=runga4(y,dydx,x,h,derive_name) % procedure uses the Runge Kutta method to % output the value yout = y(x+h) given the initial conditions % y(x) and y (x) = dydx. y can be evaluated at any x % using the function derive_name. % % yout = y(x) + h(f_0/6 + f_1/3 + f_2/3 + f_3/6), % f_0 = y (x,y) % f_1 = y (x+h/2,y+hf_0/2) % f_2 = y (x+h/2,y+hf_1/2) % f_3 = y (x+h,y+hf_2) xpick = x ; ypick = y ; f0 = feval(derive_name,xpick,ypick) ; xpick = x +.5*h ; ypick = y +.5*h*f0 ; f1 = feval(derive_name,xpick,ypick) ; ypick = y +.5*h*f1 ; f2 = feval(derive_name,xpick,ypick) ; xpick = x + h ; ypick = y + h*f2 ; f3 = feval(derive_name,xpick,ypick) ; yout = y + (h/6.)*(f0 + 2.*f1 + 2.*f2 + f3) ; return ;

21 CHAPTER 3. ORDINARY DIFFERENTIAL EQUATIONS function dydx = derivs(x,y) % this is the value of the derivative y (x) = f(x,y) % function is cos(x), thus y (x,y) = -sin(x y) dydx = -sin(x*y) ; return ;... However, sometimes it is not clear what stepsize to use. One common method is to try one step size, then halve it and try again, comparing the results, and stopping when the result converges. If time is not a big concern, simply halve the step size and compare the answers. Use the stepsize in which the answer for that step size converges. There are much fancier methods for solving differential equations, including Richardson Extrapolation, picking a stepsize that forces the leading error term to be of the order of the tolerance, and predictor-corrector methods. Matlab has a suite of ODE solvers. ode45 is very similar to a standard 4th order Runge-Kutta method (but much more slick than the code given above!) Second Order Differential Equations Now consider the equation y = f(x, y, y ) (3.13) If we let y 1 = y and y 2 = y 1, then y 1 = y 2 = f 1 (x, y 1, y 2 ) (3.14) y 2 = y 1 = f 2(x, y 1, y 2 ). (3.15) Therefore the original second order ODE is reduced to two first order ODEs. All the methods previously discussed for solving for scalar ODEs carry over to ODEs of a vector, where y = f(x,y). (3.16) Here, y(1) = y 1 and y(2) = y 2. Matlab is great at dealing with vectors. All the routines above will happily pass vectors instead of scalars. All that needs to be done is to set up the function derivs component by component, and to set up the initial conditions of the function y. Example: The simple pendulum revisited: We will now solve for θ(t) where d 2 θ dt 2 = g l sin(θ). (3.17)

22 CHAPTER 3. ORDINARY DIFFERENTIAL EQUATIONS 21 If y 1 = θ and y 2 = y 1, then f 1 = y 2 and f 2 = (g/l) sin(y 1 ). Then the function derivs may look like: function f=derivs(t,y) f(1) = y(2) ; f(2) = -(g/l)sin(y(1)) ; return ; In the main driver, the initial conditions would be ystart(1) = θ 0 and ystart(2) = θ(t = 0).

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose

More information

Introduction to Matlab

Introduction to Matlab What is Matlab? Introduction to Matlab Matlab is software written by a company called The Mathworks (mathworks.com), and was first created in 1984 to be a nice front end to the numerical routines created

More information

ODEs occur quite often in physics and astrophysics: Wave Equation in 1-D stellar structure equations hydrostatic equation in atmospheres orbits

ODEs occur quite often in physics and astrophysics: Wave Equation in 1-D stellar structure equations hydrostatic equation in atmospheres orbits Solving ODEs General Stuff ODEs occur quite often in physics and astrophysics: Wave Equation in 1-D stellar structure equations hydrostatic equation in atmospheres orbits need workhorse solvers to deal

More information

Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression.

Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression. What is the answer? >> Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression. The finite(x)is true for all finite numerical

More information

Euler s Methods (a family of Runge- Ku9a methods)

Euler s Methods (a family of Runge- Ku9a methods) Euler s Methods (a family of Runge- Ku9a methods) ODE IVP An Ordinary Differential Equation (ODE) is an equation that contains a function having one independent variable: The equation is coupled with an

More information

1 Introduction to Matlab

1 Introduction to Matlab 1 Introduction to Matlab 1. What is Matlab? Matlab is a computer program designed to do mathematics. You might think of it as a super-calculator. That is, once Matlab has been started, you can enter computations,

More information

MATLAB Introduction to MATLAB Programming

MATLAB Introduction to MATLAB Programming MATLAB Introduction to MATLAB Programming MATLAB Scripts So far we have typed all the commands in the Command Window which were executed when we hit Enter. Although every MATLAB command can be executed

More information

over The idea is to construct an algorithm to solve the IVP ODE (9.1)

over The idea is to construct an algorithm to solve the IVP ODE (9.1) Runge- Ku(a Methods Review of Heun s Method (Deriva:on from Integra:on) The idea is to construct an algorithm to solve the IVP ODE (9.1) over To obtain the solution point we can use the fundamental theorem

More information

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial Vb

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial Vb Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial Vb Making Plots with Matlab (last updated 5/29/05 by GGB) Objectives: These tutorials are

More information

Matlab Tutorial 1: Working with variables, arrays, and plotting

Matlab Tutorial 1: Working with variables, arrays, and plotting Matlab Tutorial 1: Working with variables, arrays, and plotting Setting up Matlab First of all, let's make sure we all have the same layout of the different windows in Matlab. Go to Home Layout Default.

More information

2.9 Linear Approximations and Differentials

2.9 Linear Approximations and Differentials 2.9 Linear Approximations and Differentials 2.9.1 Linear Approximation Consider the following graph, Recall that this is the tangent line at x = a. We had the following definition, f (a) = lim x a f(x)

More information

MAT 275 Laboratory 1 Introduction to MATLAB

MAT 275 Laboratory 1 Introduction to MATLAB MATLAB sessions: Laboratory 1 1 MAT 275 Laboratory 1 Introduction to MATLAB MATLAB is a computer software commonly used in both education and industry to solve a wide range of problems. This Laboratory

More information

Ordinary differential equations solving methods

Ordinary differential equations solving methods Radim Hošek, A07237 radhost@students.zcu.cz Ordinary differential equations solving methods Problem: y = y2 (1) y = x y (2) y = sin ( + y 2 ) (3) Where it is possible we try to solve the equations analytically,

More information

2nd Year Computational Physics Week 1 (experienced): Series, sequences & matrices

2nd Year Computational Physics Week 1 (experienced): Series, sequences & matrices 2nd Year Computational Physics Week 1 (experienced): Series, sequences & matrices 1 Last compiled September 28, 2017 2 Contents 1 Introduction 5 2 Prelab Questions 6 3 Quick check of your skills 9 3.1

More information

MATLAB TUTORIAL WORKSHEET

MATLAB TUTORIAL WORKSHEET MATLAB TUTORIAL WORKSHEET What is MATLAB? Software package used for computation High-level programming language with easy to use interactive environment Access MATLAB at Tufts here: https://it.tufts.edu/sw-matlabstudent

More information

Exercises for a Numerical Methods Course

Exercises for a Numerical Methods Course Exercises for a Numerical Methods Course Brian Heinold Department of Mathematics and Computer Science Mount St. Mary s University November 18, 2017 1 / 73 About the class Mix of Math and CS students, mostly

More information

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University Interactive Computing with Matlab Gerald W. Recktenwald Department of Mechanical Engineering Portland State University gerry@me.pdx.edu Starting Matlab Double click on the Matlab icon, or on unix systems

More information

4 Visualization and. Approximation

4 Visualization and. Approximation 4 Visualization and Approximation b A slope field for the differential equation y tan(x + y) tan(x) tan(y). It is not always possible to write down an explicit formula for the solution to a differential

More information

MATLAB SUMMARY FOR MATH2070/2970

MATLAB SUMMARY FOR MATH2070/2970 MATLAB SUMMARY FOR MATH2070/2970 DUNCAN SUTHERLAND 1. Introduction The following is inted as a guide containing all relevant Matlab commands and concepts for MATH2070 and 2970. All code fragments should

More information

Computer Simulations

Computer Simulations Computer Simulations A practical approach to simulation Semra Gündüç gunduc@ankara.edu.tr Ankara University Faculty of Engineering, Department of Computer Engineering 2014-2015 Spring Term Ankara University

More information

Mechanical Engineering Department Second Year (2015)

Mechanical Engineering Department Second Year (2015) Lecture 7: Graphs Basic Plotting MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. This section describes a few of the most

More information

= f (a, b) + (hf x + kf y ) (a,b) +

= f (a, b) + (hf x + kf y ) (a,b) + Chapter 14 Multiple Integrals 1 Double Integrals, Iterated Integrals, Cross-sections 2 Double Integrals over more general regions, Definition, Evaluation of Double Integrals, Properties of Double Integrals

More information

Math Scientific Computing - Matlab Intro and Exercises: Spring 2003

Math Scientific Computing - Matlab Intro and Exercises: Spring 2003 Math 64 - Scientific Computing - Matlab Intro and Exercises: Spring 2003 Professor: L.G. de Pillis Time: TTh :5pm 2:30pm Location: Olin B43 February 3, 2003 Matlab Introduction On the Linux workstations,

More information

Introduction to Programming for Engineers Spring Final Examination. May 10, Questions, 170 minutes

Introduction to Programming for Engineers Spring Final Examination. May 10, Questions, 170 minutes Final Examination May 10, 2011 75 Questions, 170 minutes Notes: 1. Before you begin, please check that your exam has 28 pages (including this one). 2. Write your name and student ID number clearly on your

More information

Programming 1. Script files. help cd Example:

Programming 1. Script files. help cd Example: Programming Until now we worked with Matlab interactively, executing simple statements line by line, often reentering the same sequences of commands. Alternatively, we can store the Matlab input commands

More information

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations MATLAB Tutorial The following tutorial has been compiled from several resources including the online Help menu of MATLAB. It contains a list of commands that will be directly helpful for understanding

More information

Math 113 Exam 1 Practice

Math 113 Exam 1 Practice Math Exam Practice January 6, 00 Exam will cover sections 6.-6.5 and 7.-7.5 This sheet has three sections. The first section will remind you about techniques and formulas that you should know. The second

More information

PART 1 PROGRAMMING WITH MATHLAB

PART 1 PROGRAMMING WITH MATHLAB PART 1 PROGRAMMING WITH MATHLAB Presenter: Dr. Zalilah Sharer 2018 School of Chemical and Energy Engineering Universiti Teknologi Malaysia 23 September 2018 Programming with MATHLAB MATLAB Environment

More information

MATLAB primer for CHE 225

MATLAB primer for CHE 225 MATLAB primer for CHE 225 The following pages contain a brief description of the MATLAB features are used in CHE 225. This document is best used in conjunction with the MATLAB codes posted on Vista. Find

More information

1.00 Lecture 32. Integration. Reading for next time: Numerical Recipes Packaging Functions in Objects

1.00 Lecture 32. Integration. Reading for next time: Numerical Recipes Packaging Functions in Objects 1.00 Lecture 32 Integration Reading for next time: Numerical Recipes 347-368 Packaging Functions in Objects Consider writing a method that evaluates, integrates or finds the roots of a function: Evaluate:

More information

over The idea is to construct an algorithm to solve the IVP ODE (8.1)

over The idea is to construct an algorithm to solve the IVP ODE (8.1) Runge- Ku(a Methods Review of Heun s Method (Deriva:on from Integra:on) The idea is to construct an algorithm to solve the IVP ODE (8.1) over To obtain the solution point we can use the fundamental theorem

More information

Introduction to Matlab

Introduction to Matlab Introduction to Matlab November 22, 2013 Contents 1 Introduction to Matlab 1 1.1 What is Matlab.................................. 1 1.2 Matlab versus Maple............................... 2 1.3 Getting

More information

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example: Using MATLAB for Stochastic Simulation. Eric W. Hansen. Matlab Basics Introduction MATLAB (MATrix LABoratory) is a software package designed for efficient, reliable numerical computing. Using MATLAB greatly

More information

MATLAB Tutorial III Variables, Files, Advanced Plotting

MATLAB Tutorial III Variables, Files, Advanced Plotting MATLAB Tutorial III Variables, Files, Advanced Plotting A. Dealing with Variables (Arrays and Matrices) Here's a short tutorial on working with variables, taken from the book, Getting Started in Matlab.

More information

Mathematics for chemical engineers

Mathematics for chemical engineers Mathematics for chemical engineers Drahoslava Janovská Department of mathematics Winter semester 2013-2014 Numerical solution of ordinary differential equations Initial value problem Outline 1 Introduction

More information

MATH2071: LAB 2: Explicit ODE methods

MATH2071: LAB 2: Explicit ODE methods MATH2071: LAB 2: Explicit ODE methods 1 Introduction Introduction Exercise 1 Euler s method review Exercise 2 The Euler Halfstep (RK2) Method Exercise 3 Runge-Kutta Methods Exercise 4 The Midpoint Method

More information

Evaluating the polynomial at a point

Evaluating the polynomial at a point Evaluating the polynomial at a point Recall that we have a data structure for each piecewise polynomial (linear, quadratic, cubic and cubic Hermite). We have a routine that sets evenly spaced interpolation

More information

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text Chapter 1 Getting Started How to Get Matlab Matlab physically resides on each of the computers in the Olin Hall labs. See your instructor if you need an account on these machines. If you are going to go

More information

3.3 Optimizing Functions of Several Variables 3.4 Lagrange Multipliers

3.3 Optimizing Functions of Several Variables 3.4 Lagrange Multipliers 3.3 Optimizing Functions of Several Variables 3.4 Lagrange Multipliers Prof. Tesler Math 20C Fall 2018 Prof. Tesler 3.3 3.4 Optimization Math 20C / Fall 2018 1 / 56 Optimizing y = f (x) In Math 20A, we

More information

Grace days can not be used for this assignment

Grace days can not be used for this assignment CS513 Spring 19 Prof. Ron Matlab Assignment #0 Prepared by Narfi Stefansson Due January 30, 2019 Grace days can not be used for this assignment The Matlab assignments are not intended to be complete tutorials,

More information

John Perry. Spring 2016

John Perry. Spring 2016 MAT 305: Repeating a task on a set (or list, or tuple, or...) University of Southern Mississippi Spring 2016 Outline 1 2 3 4 5 6 7 Outline 1 2 3 4 5 6 7 Differential Equations What is y in terms of x?

More information

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed. Example 4 Printing and Plotting Matlab provides numerous print and plot options. This example illustrates the basics and provides enough detail that you can use it for typical classroom work and assignments.

More information

ODE IVP. An Ordinary Differential Equation (ODE) is an equation that contains a function having one independent variable:

ODE IVP. An Ordinary Differential Equation (ODE) is an equation that contains a function having one independent variable: Euler s Methods ODE IVP An Ordinary Differential Equation (ODE) is an equation that contains a function having one independent variable: The equation is coupled with an initial value/condition (i.e., value

More information

Numerical Methods for Differential Equations Contents Review of numerical integration methods Rectangular Rule Trapezoidal Rule Simpson s Rule How to

Numerical Methods for Differential Equations Contents Review of numerical integration methods Rectangular Rule Trapezoidal Rule Simpson s Rule How to Numerical Methods for Differential Equations Contents Review of numerical integration methods Rectangular Rule Trapezoidal Rule Simpson s Rule How to make a connect-the-dots graphic Numerical Methods for

More information

A = [1, 6; 78, 9] Note: everything is case-sensitive, so a and A are different. One enters the above matrix as

A = [1, 6; 78, 9] Note: everything is case-sensitive, so a and A are different. One enters the above matrix as 1 Matlab Primer The purpose of these notes is a step-by-step guide to solving simple optimization and root-finding problems in Matlab To begin, the basic object in Matlab is an array; in two dimensions,

More information

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

Prof. Manoochehr Shirzaei. RaTlab.asu.edu RaTlab.asu.edu Introduction To MATLAB Introduction To MATLAB This lecture is an introduction of the basic MATLAB commands. We learn; Functions Procedures for naming and saving the user generated files

More information

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB? Appendix A Introduction to MATLAB A.1 What Is MATLAB? MATLAB is a technical computing environment developed by The Math- Works, Inc. for computation and data visualization. It is both an interactive system

More information

Computers in Engineering Root Finding Michael A. Hawker

Computers in Engineering Root Finding Michael A. Hawker Computers in Engineering COMP 208 Root Finding Michael A. Hawker Root Finding Many applications involve finding the roots of a function f(x). That is, we want to find a value or values for x such that

More information

MATLAB Guide to Fibonacci Numbers

MATLAB Guide to Fibonacci Numbers MATLAB Guide to Fibonacci Numbers and the Golden Ratio A Simplified Approach Peter I. Kattan Petra Books www.petrabooks.com Peter I. Kattan, PhD Correspondence about this book may be sent to the author

More information

Algebra 2 Semester 1 (#2221)

Algebra 2 Semester 1 (#2221) Instructional Materials for WCSD Math Common Finals The Instructional Materials are for student and teacher use and are aligned to the 2016-2017 Course Guides for the following course: Algebra 2 Semester

More information

ChE 400: Applied Chemical Engineering Calculations Tutorial 6: Numerical Solution of ODE Using Excel and Matlab

ChE 400: Applied Chemical Engineering Calculations Tutorial 6: Numerical Solution of ODE Using Excel and Matlab ChE 400: Applied Chemical Engineering Calculations Tutorial 6: Numerical Solution of ODE Using Excel and Matlab Tutorial 6: Numerical Solution of ODE Gerardine G. Botte This handout contains information

More information

Laboratory 1 Octave Tutorial

Laboratory 1 Octave Tutorial Signals, Spectra and Signal Processing Laboratory 1 Octave Tutorial 1.1 Introduction The purpose of this lab 1 is to become familiar with the GNU Octave 2 software environment. 1.2 Octave Review All laboratory

More information

MAT 275 Laboratory 3 Numerical Solutions by Euler and Improved Euler Methods (scalar equations)

MAT 275 Laboratory 3 Numerical Solutions by Euler and Improved Euler Methods (scalar equations) MATLAB sessions: Laboratory 3 1 MAT 275 Laboratory 3 Numerical Solutions by Euler and Improved Euler Methods (scalar equations) In this session we look at basic numerical methods to help us understand

More information

2 Amazingly Simple Example Suppose we wanted to represent the following matrix 2 itchy = To enter itchy in Matla

2 Amazingly Simple Example Suppose we wanted to represent the following matrix 2 itchy = To enter itchy in Matla Superlative-Laced Matlab Help for ECE155 Students Brian Kurkoski kurkoski@ucsd.edu October 13, 1999 This document is an introduction to Matlab for ECE155 students. It emphasizes the aspects of Matlab that

More information

This module aims to introduce Precalculus high school students to the basic capabilities of Matlab by using functions. Matlab will be used in

This module aims to introduce Precalculus high school students to the basic capabilities of Matlab by using functions. Matlab will be used in This module aims to introduce Precalculus high school students to the basic capabilities of Matlab by using functions. Matlab will be used in subsequent modules to help to teach research related concepts

More information

MA 114 Worksheet #17: Average value of a function

MA 114 Worksheet #17: Average value of a function Spring 2019 MA 114 Worksheet 17 Thursday, 7 March 2019 MA 114 Worksheet #17: Average value of a function 1. Write down the equation for the average value of an integrable function f(x) on [a, b]. 2. Find

More information

AMS 27L LAB #2 Winter 2009

AMS 27L LAB #2 Winter 2009 AMS 27L LAB #2 Winter 2009 Plots and Matrix Algebra in MATLAB Objectives: 1. To practice basic display methods 2. To learn how to program loops 3. To learn how to write m-files 1 Vectors Matlab handles

More information

Introduction to Matlab

Introduction to Matlab What is Matlab? Introduction to Matlab Matlab is a computer program designed to do mathematics. You might think of it as a super-calculator. That is, once Matlab has been started, you can enter computations,

More information

Linear algebra deals with matrixes: two-dimensional arrays of values. Here s a matrix: [ x + 5y + 7z 9x + 3y + 11z

Linear algebra deals with matrixes: two-dimensional arrays of values. Here s a matrix: [ x + 5y + 7z 9x + 3y + 11z Basic Linear Algebra Linear algebra deals with matrixes: two-dimensional arrays of values. Here s a matrix: [ 1 5 ] 7 9 3 11 Often matrices are used to describe in a simpler way a series of linear equations.

More information

Review Initial Value Problems Euler s Method Summary

Review Initial Value Problems Euler s Method Summary THE EULER METHOD P.V. Johnson School of Mathematics Semester 1 2008 OUTLINE 1 REVIEW 2 INITIAL VALUE PROBLEMS The Problem Posing a Problem 3 EULER S METHOD Method Errors 4 SUMMARY OUTLINE 1 REVIEW 2 INITIAL

More information

Dynamics and Vibrations Mupad tutorial

Dynamics and Vibrations Mupad tutorial Dynamics and Vibrations Mupad tutorial School of Engineering Brown University ENGN40 will be using Matlab Live Scripts instead of Mupad. You can find information about Live Scripts in the ENGN40 MATLAB

More information

The Bisection Method versus Newton s Method in Maple (Classic Version for Windows)

The Bisection Method versus Newton s Method in Maple (Classic Version for Windows) The Bisection Method versus (Classic Version for Windows) Author: Barbara Forrest Contact: baforres@uwaterloo.ca Copyrighted/NOT FOR RESALE version 1.1 Contents 1 Objectives for this Lab i 2 Approximate

More information

Introduction to Matlab to Accompany Linear Algebra. Douglas Hundley Department of Mathematics and Statistics Whitman College

Introduction to Matlab to Accompany Linear Algebra. Douglas Hundley Department of Mathematics and Statistics Whitman College Introduction to Matlab to Accompany Linear Algebra Douglas Hundley Department of Mathematics and Statistics Whitman College August 27, 2018 2 Contents 1 Getting Started 5 1.1 Before We Begin........................................

More information

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment What is MATLAB? MATLAB PROGRAMMING Stands for MATrix LABoratory A software built around vectors and matrices A great tool for numerical computation of mathematical problems, such as Calculus Has powerful

More information

Summer 2009 REU: Introduction to Matlab

Summer 2009 REU: Introduction to Matlab Summer 2009 REU: Introduction to Matlab Moysey Brio & Paul Dostert June 29, 2009 1 / 19 Using Matlab for the First Time Click on Matlab icon (Windows) or type >> matlab & in the terminal in Linux. Many

More information

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab Islamic University of Gaza Faculty of Engineering Electrical Engineering Department 2012 DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab Goals for this Lab Assignment: In this lab we would have

More information

Today s class. Roots of equation Finish up incremental search Open methods. Numerical Methods, Fall 2011 Lecture 5. Prof. Jinbo Bi CSE, UConn

Today s class. Roots of equation Finish up incremental search Open methods. Numerical Methods, Fall 2011 Lecture 5. Prof. Jinbo Bi CSE, UConn Today s class Roots of equation Finish up incremental search Open methods 1 False Position Method Although the interval [a,b] where the root becomes iteratively closer with the false position method, unlike

More information

Homework Set #2-3, Math 475B

Homework Set #2-3, Math 475B Homework Set #2-3, Math 475B Part I: Matlab In the last semester you learned a number of essential features of MATLAB. 1. In this instance, you will learn to make 3D plots and contour plots of z = f(x,

More information

NUMERICAL INTEGRATION

NUMERICAL INTEGRATION NUMERICAL INTEGRATION f(x) MISN-0-349 NUMERICAL INTEGRATION by Robert Ehrlich George Mason University 1. Numerical Integration Algorithms a. Introduction.............................................1 b.

More information

y= sin( x) y= cos( x)

y= sin( x) y= cos( x) . The graphs of sin(x) and cos(x). Now I am going to define the two basic trig functions: sin(x) and cos(x). Study the diagram at the right. The circle has radius. The arm OP starts at the positive horizontal

More information

8 Piecewise Polynomial Interpolation

8 Piecewise Polynomial Interpolation Applied Math Notes by R. J. LeVeque 8 Piecewise Polynomial Interpolation 8. Pitfalls of high order interpolation Suppose we know the value of a function at several points on an interval and we wish to

More information

Partial Derivatives (Online)

Partial Derivatives (Online) 7in x 10in Felder c04_online.tex V3 - January 21, 2015 9:44 A.M. Page 1 CHAPTER 4 Partial Derivatives (Online) 4.7 Tangent Plane Approximations and Power Series It is often helpful to use a linear approximation

More information

18.02 Multivariable Calculus Fall 2007

18.02 Multivariable Calculus Fall 2007 MIT OpenCourseWare http://ocw.mit.edu 18.02 Multivariable Calculus Fall 2007 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 18.02 Problem Set 4 Due Thursday

More information

Matlab Tutorial and Exercises for COMP61021

Matlab Tutorial and Exercises for COMP61021 Matlab Tutorial and Exercises for COMP61021 1 Introduction This is a brief Matlab tutorial for students who have not used Matlab in their programming. Matlab programming is essential in COMP61021 as a

More information

Math 225 Scientific Computing II Outline of Lectures

Math 225 Scientific Computing II Outline of Lectures Math 225 Scientific Computing II Outline of Lectures Spring Semester 2003 I. Interpolating polynomials Lagrange formulation of interpolating polynomial Uniqueness of interpolating polynomial of degree

More information

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming using familiar mathematical notation The name Matlab stands

More information

Math F302: Octave Miscellany September 28, e 1 x3 dx. Here s how to find a numerical approximation with Octave

Math F302: Octave Miscellany September 28, e 1 x3 dx. Here s how to find a numerical approximation with Octave Definite Integrals Despite your training in Calculus, most definite integrals cannot be computed exactly, and must be approximated numerically. You learned a number of rules for doing this: the trapezoidal

More information

fplot Syntax Description Examples Plot Symbolic Expression Plot symbolic expression or function fplot(f) fplot(f,[xmin xmax])

fplot Syntax Description Examples Plot Symbolic Expression Plot symbolic expression or function fplot(f) fplot(f,[xmin xmax]) fplot Plot symbolic expression or function Syntax fplot(f) fplot(f,[xmin xmax]) fplot(xt,yt) fplot(xt,yt,[tmin tmax]) fplot(,linespec) fplot(,name,value) fplot(ax, ) fp = fplot( ) Description fplot(f)

More information

Introduction to C++ Introduction to C++ Week 6 Dr Alex Martin 2013 Slide 1

Introduction to C++ Introduction to C++ Week 6 Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Week 6 Dr Alex Martin 2013 Slide 1 Numerical Integration Methods The Trapezoidal Rule If one has an arbitrary function f(x) to be integrated over the region [a,b]

More information

PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as Geog 271 Geographic Data Analysis Fall 2017 PyPlot Graphicscanbeproducedin Pythonviaavarietyofpackages. We willuseapythonplotting package that is part of MatPlotLib, for which documentation can be found

More information

AQA GCSE Further Maths Topic Areas

AQA GCSE Further Maths Topic Areas AQA GCSE Further Maths Topic Areas This document covers all the specific areas of the AQA GCSE Further Maths course, your job is to review all the topic areas, answering the questions if you feel you need

More information

R f da (where da denotes the differential of area dxdy (or dydx)

R f da (where da denotes the differential of area dxdy (or dydx) Math 28H Topics for the second exam (Technically, everything covered on the first exam, plus) Constrained Optimization: Lagrange Multipliers Most optimization problems that arise naturally are not unconstrained;

More information

MEI GeoGebra Tasks for A2 Core

MEI GeoGebra Tasks for A2 Core Task 1: Functions The Modulus Function 1. Plot the graph of y = x : use y = x or y = abs(x) 2. Plot the graph of y = ax+b : use y = ax + b or y = abs(ax+b) If prompted click Create Sliders. What combination

More information

EE 301 Lab 1 Introduction to MATLAB

EE 301 Lab 1 Introduction to MATLAB EE 301 Lab 1 Introduction to MATLAB 1 Introduction In this lab you will be introduced to MATLAB and its features and functions that are pertinent to EE 301. This lab is written with the assumption that

More information

PHYSICS 115/242 Homework 2, Solutions

PHYSICS 115/242 Homework 2, Solutions PHYSICS 115/242 Homework 2, Solutions 1. Trapezium Rule I wrote a function trap to do the trapezoidal rule, and put it in a separate file, trap.c. This is as follows: /******************************************************************

More information

What is Matlab? A software environment for interactive numerical computations

What is Matlab? A software environment for interactive numerical computations What is Matlab? A software environment for interactive numerical computations Examples: Matrix computations and linear algebra Solving nonlinear equations Numerical solution of differential equations Mathematical

More information

MATLAB Vocabulary. Gerald Recktenwald. Version 0.965, 25 February 2017

MATLAB Vocabulary. Gerald Recktenwald. Version 0.965, 25 February 2017 MATLAB Vocabulary Gerald Recktenwald Version 0.965, 25 February 2017 MATLAB is a software application for scientific computing developed by the Mathworks. MATLAB runs on Windows, Macintosh and Unix operating

More information

CS1114: Matlab Introduction

CS1114: Matlab Introduction CS1114: Matlab Introduction 1 Introduction The purpose of this introduction is to provide you a brief introduction to the features of Matlab that will be most relevant to your work in this course. Even

More information

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah) Introduction ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah) MATLAB is a powerful mathematical language that is used in most engineering companies today. Its strength lies

More information

Introduction to Matlab

Introduction to Matlab Introduction to Matlab What is Matlab The software program called Matlab (short for MATrix LABoratory) is arguably the world standard for engineering- mainly because of its ability to do very quick prototyping.

More information

Chapter 3: Introduction to MATLAB Programming (4 th ed.)

Chapter 3: Introduction to MATLAB Programming (4 th ed.) Chapter 3: Introduction to MATLAB Programming (4 th ed.) Algorithms MATLAB scripts Input / Output o disp versus fprintf Graphs Read and write variables (.mat files) User-defined Functions o Definition

More information

Numerical Methods Lecture 7 - Optimization

Numerical Methods Lecture 7 - Optimization Numerical Methods Lecture 7 - Optimization Topics: numerical optimization - Newton again - Random search - Golden Section Search READING : text pgs. 331-349 Optimization - motivation What? Locating where

More information

Matlab Introduction. Scalar Variables and Arithmetic Operators

Matlab Introduction. Scalar Variables and Arithmetic Operators Matlab Introduction Matlab is both a powerful computational environment and a programming language that easily handles matrix and complex arithmetic. It is a large software package that has many advanced

More information

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER BENC 2113 DENC ECADD 2532 ECADD LAB SESSION 6/7 LAB

More information

B.Stat / B.Math. Entrance Examination 2017

B.Stat / B.Math. Entrance Examination 2017 B.Stat / B.Math. Entrance Examination 017 BOOKLET NO. TEST CODE : UGA Forenoon Questions : 0 Time : hours Write your Name, Registration Number, Test Centre, Test Code and the Number of this Booklet in

More information

Basic Graphs. Dmitry Adamskiy 16 November 2011

Basic Graphs. Dmitry Adamskiy 16 November 2011 Basic Graphs Dmitry Adamskiy adamskiy@cs.rhul.ac.uk 16 November 211 1 Plot Function plot(x,y): plots vector Y versus vector X X and Y must have the same size: X = [x1, x2 xn] and Y = [y1, y2,, yn] Broken

More information

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain Introduction to Matlab By: Dr. Maher O. EL-Ghossain Outline: q What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control

More information

Here is a quick introduction to Matlab and a couple of its symbolic and control functions.

Here is a quick introduction to Matlab and a couple of its symbolic and control functions. Some Matlab 1 Here is a quick introduction to Matlab and a couple of its symbolic and control functions. Matlab is an interpreted language. When you enter a command in the Command window, the line is executed

More information

Computational Modelling 102 (Scientific Programming) Tutorials

Computational Modelling 102 (Scientific Programming) Tutorials COMO 102 : Scientific Programming, Tutorials 2003 1 Computational Modelling 102 (Scientific Programming) Tutorials Dr J. D. Enlow Last modified August 18, 2003. Contents Tutorial 1 : Introduction 3 Tutorial

More information

APPM 2460 PLOTTING IN MATLAB

APPM 2460 PLOTTING IN MATLAB APPM 2460 PLOTTING IN MATLAB. Introduction Matlab is great at crunching numbers, and one of the fundamental ways that we understand the output of this number-crunching is through visualization, or plots.

More information