Essential MATLAB for Engineers and Scientists PHẦN 6 pptx

44 967 0
Essential MATLAB for Engineers and Scientists PHẦN 6 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Ch07-H8417 6/1/2007 16: 16 page 201 7 Introduction to graphics ➤ The polar command plots in polar coordinates. ➤ fplot provides a handy way of plotting mathematical functions. ➤ plot3 draws lines in 3-D. ➤ comet3 animates a 3-D plot. ➤ A 3-D surface may be plotted with mesh. ➤ A 3-D plot may be rotated with view or with the Rotate 3-D tool in the figure window. ➤ mesh may also be used to visualize a matrix. ➤ contour and countour3 draws contour levels in 2-D and 3-D respectively. ➤ 3-D surfaces may be cropped. ➤ For a complete list of graphics functions consult the online Help in MATLAB Function Reference: Functions by Category: Graphics. EXERCISES 7.1 Draw a graph of the population of the USA from 1790 to 2000, using the (logistic) model P(t) = 19 72 73 000 1 +e −0.03134(t−1913.25) where t is the date in years. Actual data (in 1000s) for every decade from 1790 to 1950 are as follows: 3929, 5308, 7240, 9638, 12 866, 17 069, 23 192, 31 443, 38 558, 50 156, 62 948, 75 995, 91 972, 105 711, 122 775, 131 669, 150 697. Superimpose this data on the graph of P(t). Plot the data as discrete circles (i.e. do not join them with lines) as shown in Figure 7.14. 7.2 The Spiral of Archimedes (Figure 7.15(a)) may be represented in polar coordinates by the equation r = aθ, where a is some constant. (The shells of a class of animals called nummulites grow in this way.) Write some command-line statements to draw the spiral for some values of a. 7.3 Another type of spiral is the logarithmic spiral (Figure 7.15(b)), which describes the growth of shells of animals like the periwinkle and the nautilus. Its equation 201 Ch07-H8417 6/1/2007 16: 16 page 202 Essential MATLAB for Engineers and Scientists in polar coordinates is r = aq θ , where a > 0, q > 1. Draw this spiral. 1750 Population size 1800 1850 1900 Year 1950 2000 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 ϫ 10 8 Figure 7.14 USA population: model and census data (o) Archimedes (a) (b) Logarithmic Figure 7.15 Spirals 202 Ch07-H8417 6/1/2007 16: 16 page 203 7 Introduction to graphics 7.4 The arrangement of seeds in a sunflower head (and other flowers, like daisies) follows a fixed mathematical pattern. The nth seed is at position r = √ n, Figure 7.16 A perfect sunflower? with angular coordinate πdn/180 radians, where d is the constant angle of divergence (in degrees) between any two successive seeds, i.e. between the nth and (n +1)th seeds. A perfect sunflower head (Figure 7.16) is generated by d =137.51 ◦ . Write a program to plot the seeds; use a circle (o) for each seed. A remarkable feature of this model is that the angle d must be exact to get proper sunflowers. Experiment with some different values, e.g. 137.45 ◦ (spokes, from fairly far out), 137.65 ◦ (spokes all the way), 137.92 ◦ (Catherine wheels). 7.5 The equation of an ellipse in polar coordinates is given by r = a(1 − e 2 )/(1 −e cos θ), where a is the semi-major axis and e is the eccentricity, if one focus is at the origin, and the semi-major axis lies on the x-axis. 203 Ch07-H8417 6/1/2007 16: 16 page 204 Essential MATLAB for Engineers and Scientists Halley’s Comet, which visited us in 1985/6, moves in an elliptical orbit about the Sun (at one focus) with a semi-major axis of 17.9 A.U. (A.U. stands for Astronomical Unit, which is the mean distance of the Earth from the Sun: 149.6 million km.) The eccentricity of the orbit is 0.967276. Write a program which draws the orbit of Halley’s Comet and the Earth (assume the Earth is circular). 7.6 A very interesting iterative relationship that has been studied a lot recently is defined by y k+1 = ry k (1 −y k ) (this is a discrete form of the well-known logistic model). Given y 0 and r, successive y k ’s may be computed very easily, e.g. if y 0 =0.2 and r =1, then y 1 =0.16, y 2 =0.1334, and so on. This formula is often used to model population growth in cases where the growth is not unlimited, but is restricted by shortage of food, living area, etc. y k exhibits fascinating behavior, known as mathematical chaos, for values of r between 3 and 4 (independent of y 0 ). Write a program which plots y k against k (as individual points). Values of r that give particularly interesting graphs are 3.3, 3.5, 3.5668, 3.575, 3.5766, 3.738, 3.8287, and many more that can be found by patient exploration. 7.7 A rather beautiful fractal picture can be drawn by plotting the points (x k , y k ) generated by the following difference equations x k+1 = y k (1 +sin 0.7x k ) −1.2  |x k |, y k+1 = 0.21 −x k , starting with x 0 =y 0 =0. Write a program to draw the picture (plot individual points; do not join them). 204 Ch08-H8417 5/1/2007 11: 39 page 205 8 Loops The objectives of this chapter are to enable you to learn to: ➤ Program (or code) determinate loops with for. ➤ Program (or code) indeterminate loops with while. In Chapter 2 we introduced the powerful for statement, which is used to repeat a block of statements a fixed number of times. This type of structure, where the number of repetitions must be determined in advance, is sometimes called determinate repetition. However, it often happens that the condition to end a loop is only satisfied during the execution of the loop itself. Such a structure is called indeterminate. This chapter is mainly about indeterminate loops, but to emphasize the difference between the two types of repetition we will first look at some more examples of for loops. 8.1 Determinate repetition with for 8.1.1 Binomial coefficient The binomial coefficient is widely used in mathematics and statistics. It is defined as the number of ways of choosing r objects out of n without regard to order, and is given by  n r  = n! r!(n − r)! . (8.1) If this form is used, the factorials can get very big, causing an overflow. But a little thought reveals we can simplify Equation (8.1) as follows:  n r  = n(n −1)(n −2) ···(n −r +1) r! , (8.2) Ch08-H8417 5/1/2007 11: 39 page 206 Essential MATLAB for Engineers and Scientists e.g.  10 3  = 10! 3!×7! = 10 ×9 ×8 1 ×2 ×3 . Using Equation (8.2) is computationally much more efficient: ncr=1; n = r = for k = 1:r ncr=ncr*(n-k+1)/k; end disp( ncr ) The binomial coefficient is sometimes pronounced ‘n-see-r’. Work through the program by hand with some sample values. 8.1.2 Update processes Many problems in science and engineering involve modeling a process where the main variable is repeatedly updated over a period of time. Here is an example of such an update process. A can of orange juice at temperature 25 ◦ C is placed in a fridge, where the ambient temperature F is 10 ◦ C. We want to find out how the temperature of the orange juice changes over a period of time. A standard way of approaching this type of problem is to break the time period up into a number of small steps, each of length dt.IfT i is the temperature at the beginning of step i, we can use the following model to get T i+1 from T i : T i+1 = T i −Kdt(T i −F), (8.3) where K is a constant parameter depending on the insulating properties of the can, and the thermal properties of orange juice. Assume that units are chosen so that time is in minutes. The following script implements this scheme. To make the solution more gen- eral, take the starting time as a, and the end time as b.Ifdt is very small, it will be inconvenient to have output displayed after every step, so the script also asks you for the output interval opint. This is the time (in minutes) between successive rows of output. It checks that this interval is an integer multiple of dt. Try the script with some sample values, e.g. dt =0.2 minutes and opint = 5 minutes (these are the values used for the output below). 206 Ch08-H8417 5/1/2007 11: 39 page 207 8 Loops K = 0.05; F = 10; a = 0; % start time b = 100; % end time time = a; % initialize time T = 25; % initialize temperature load train % prepare to blow the whistle dt = input( ’dt: ’ ); opint = input( ’output interval (minutes): ’ ); if opint/dt ˜= fix(opint/dt) sound(y, Fs) % blow the whistle! disp( ’output interval is not a multiple of dt!’ ); break end clc format bank disp( ’ Time Temperature’ ); disp( [time T] ) % display initial values for time = a+dt : dt : b T=T-K*dt*(T-F); if abs(rem(time, opint)) < 1e-6 % practically zero! disp( [time T] ) end end Output: Time Temperature 0 25.00 5.00 21.67 95.00 10.13 100.00 10.10 Note: 1. The function rem is used to display the results every opint minutes: when time is an integer multiple of opint its remainder when divided by opint should be zero. However, due to rounding error, the remainder is not always exactly zero. It is therefore better to test whether its absolute value is less than some very small value. (Rounding error is discussed in Chapter 9). 2. While this is probably the most obvious way of writing the script, we cannot easily plot the graph of temperature against time this way, since time and 207 Ch08-H8417 5/1/2007 11: 39 page 208 Essential MATLAB for Engineers and Scientists T are scalars which are repeatedly updated. To plot the graph they both need to be vectors (see Chapter 11). 3. Note how sound is implemented. See help audio for other interesting sounds supplied by MATLAB. 4. In case you are wondering how I got the headings in the right place, I’ll let you into the secret. Run the script without a heading but with the numerical output as you want it. Then simply paste the disp statement with the headings into the command window and edit it until the headings fall in the right place. Paste the final version of the disp statement into the script. 5. Note the use of break to stop the script prematurely if the user gives bad input. See below for more general use of break. 8.1.3 Nested fors As we saw in Chapter 6 (Vectorizing nested fors), for loops can be nested inside each other. The main point to note is that the index of the inner for moves faster. 8.2 Indeterminate repetition with while Determinate loops all have in common the fact that you can work out in principle exactly how many repetitions are required before the loop starts. But in the next example, there is no way in principle of working out the number of repeats, so a different structure is needed. 8.2.1 A guessing game The problem is easy to state. MATLAB ‘thinks’ of an integer between 1 and 10 (i.e. generates one at random). You have to guess it. If your guess is too high or too low, the script must say so. If your guess is correct, a message of congratulations must be displayed. A little more thought is required here, so a structure plan might be helpful: 1. Generate random integer 2. Ask user for guess 3. While guess is wrong: If guess is too low Tell her it is too low Otherwise 208 Ch08-H8417 5/1/2007 11: 39 page 209 8 Loops Tell her it is too high Ask user for new guess 4. Polite congratulations 5. Stop. Here is the script: matnum = floor(10 * rand + 1); guess = input( ’Your guess please: ’ ); load splat while guess ˜= matnum sound(y, Fs) if guess > matnum disp( ’Too high’ ) else disp( ’Too low’ ) end; guess = input( ’Your next guess please: ’ ); end disp( ’At last!’ ) load handel sound(y, Fs) % hallelujah! Try it out a few times. Note that the while loop repeats as long as matnum is not equal to guess. There is no way in principle of knowing how many loops will be needed before the user guesses correctly. The problem is truly indeterminate. Note that guess has to be input in two places: firstly to get the while loop going, and secondly during the execution of the while. 8.2.2 The while statement In general the while statement looks like this: while condition statements end 209 Ch08-H8417 5/1/2007 11: 39 page 210 Essential MATLAB for Engineers and Scientists The while construct repeats statements WHILE its condition remains true. The condition therefore is the condition to repeat once again. The condition is tested each time BEFORE statements are repeated. Since the condition is evaluated before statements are executed, it is possible to arrange for statements not to be executed at all under certain circumstances. Clearly, condition must depend on statements in some way, otherwise the loop will never end. Recall that a vector condition is considered true only if all its elements are non-zero. The command-line form of while is: while condition statements, end 8.2.3 Doubling time of an investment Suppose we have invested some money which draws 10 percent interest per year, compounded. We would like to know how long it takes for the investment to double. More specifically, we want a statement of the account each year, until the balance has doubled. The English statement of the problem hints heavily that we should use an indeterminate loop with the following structure plan: 1. Initialize balance, year, interest rate 2. Display headings 3. Repeat Update balance according to interest rate Display year, balance until balance exceeds twice original balance 4. Stop. A program to implement this plan would be a = 1000; r = 0.1; bal=a; year = 0; disp( ’Year Balance’ ) while bal<2*a bal=bal+r*bal; year = year + 1; disp( [year bal] ) end 210 [...]... sample run (with format long e), starting with x = 1: Initial guess: 1 1.250000000000000e+000 1.214285714285714e+000 1.213412175782825e+000 1.21341 166 2 762 407e+000 1.21341 166 2 762 230e+000 2.031250000000000e-001 4.73 760 9329445558e-003 2.7790 866 665 71118e-0 06 9.583445148 564 351e-013 -4.44089209850 062 6e-0 16 Zero found at 1.21341 166 2 762 230e+000 Note: ➤ The variable y in the function files f.m and df.m is the... are 233 Essential MATLAB for Engineers and Scientists two MATLAB functions to do this (mean and std), it is useful to have them combined into one Write a function file stats.m: function [avg, stdev] = stats( x ) % STATS % % % % function definition line % H1 line Mean and standard deviation Returns mean (avg) % Help text and standard deviation (stdev) of the data in the vector x, using Matlab functions... the workspace 225 Essential MATLAB for Engineers and Scientists Furthermore, a MATLAB function hides a script of the same name, e.g create a script called why.m that displays some junk message, and then type why at the command line If you are worried that a variable or script which you are thinking of creating, say blob, may be a MATLAB function, try help blob first 9.2.3 Other pitfalls for the unwary... 4ac)/(2a) 227 Essential MATLAB for Engineers and Scientists Taking a = 1, b = −107 and c = 0.001 gives x1 = 107 and x2 = 0 The second root is expressed as the difference between two nearly equal numbers, and considerable significance is lost However, as you no doubt remember, the product of the two roots is given by c/a The second root can therefore be expressed as (c/a)/x1 Using this form gives x2... script so that it displays the last time for which y was positive (tmax), after the while loop has ended Now suppose we want to plot the trajectory, as shown in Figure 8.1 Note in particular how the trajectory stops above the x-axis We need to use vectors now Here is the script: dt = 0.1; g = 9.8; u = 60 ; 213 Essential MATLAB for Engineers and Scientists 100 90 80 70 60 50 40 30 20 10 0 0 50 100 150 200... 1.5 Essential MATLAB for Engineers and Scientists 8.7 If an amount of money A is invested for k years at a nominal annual interest rate r (expressed as a decimal fraction), the value V of the investment after k years is given by V = A(1 + r/n)nk where n is the number of compounding periods per year Write a program to compute V as n gets larger and larger, i.e as the compounding periods become more and. .. argument with inline For example, f = inline( ’x.ˆ2 + y.ˆ2’, ’x’, ’y’ ); f(1, 2) ans = 5 231 Essential MATLAB for Engineers and Scientists 10.1.2 Function M-files: Newton’s method again Newton’s method may be used to solve a general equation f (x) = 0 by repeating the assignment x becomes x − f (x) , f (x) where f (x) (i.e df /dx) is the first derivative of f (x) (see Chapter 17 for a derivation) The... reasonably allow (start modestly, with 100 terms, say, and rerun your program with more and more each time) You should find that the series converges very slowly, i.e it takes a lot of terms to get fairly close to π (b) Rearranging the series speeds up the convergence: π 1 1 1 = + + ··· 8 1 × 3 5 × 7 9 × 11 217 Essential MATLAB for Engineers and Scientists Write a program to compute π using this series... must agree This is generated for example by [1 2 3] * [4 5 6] since matrix multiplication cannot be applied to two row vectors Presumably the array operation * was intended You get a similar message after something like [1 2 3] + [4 5] because the vectors don’t have the same number of elements Missing operator, comma, or semicolon 223 Essential MATLAB for Engineers and Scientists This is a very common... file, this command displays the H1 line of each M-file in the directory ➤ Local variables: scope Any variables defined inside a function are inaccessible outside the function Such variables are called local variables—they exist only inside the 235 Essential MATLAB for Engineers and Scientists function, which has its own workspace separate from the base workspace of variables defined in the Command Window . the origin, and the semi-major axis lies on the x-axis. 203 Ch07-H8417 6/ 1/2007 16: 16 page 204 Essential MATLAB for Engineers and Scientists Halley’s Comet, which visited us in 1985 /6, moves in. growth of shells of animals like the periwinkle and the nautilus. Its equation 201 Ch07-H8417 6/ 1/2007 16: 16 page 202 Essential MATLAB for Engineers and Scientists in polar coordinates is r = aq θ , where. 1000s) for every decade from 1790 to 1950 are as follows: 3929, 5308, 7240, 963 8, 12 866 , 17 069 , 23 192, 31 443, 38 558, 50 1 56, 62 948, 75 995, 91 972, 105 711, 122 775, 131 66 9, 150 69 7. Superimpose this

Ngày đăng: 12/08/2014, 16:22

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan