Example: tourism industry

Chapter 1 Introduction to MATLAB - MathWorks

Chapter 1 Introduction to MATLABThis book is an Introduction to two subjects:Matlaband numerical first Chapter introducesMatlabby presenting several programs that inves-tigate elementary, but interesting, mathematical problems. If you already havesome experience programming in another language, we hope that you can see howMatlabworks by simply studying these you want a more comprehensive Introduction , there are many resourcesavailable. You can select theHelptab in the toolstrip atop theMatlabcom-mand window, then selectDocumentation,MATLABandGetting MathWorks Web site, MATLAB Tutorials and Learning Resources[11], offersa number of introductory videos and a PDF manual entitledGetting Started Introduction to MATLAB through a collection of mathematical and com-putational projects is provided by Moler s free onlineExperiments with MATLAB [6].

This book is an introduction to two subjects: Matlab and numerical computing. This first chapter introduces Matlab by presenting several programs that inves- ... The following Matlab program produces the picture of the golden rectangle shown in Figure 1.1. The program is contained in an M-file named goldrect.m, so issuing the command

Tags:

  Book, Pictures

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Transcription of Chapter 1 Introduction to MATLAB - MathWorks

1 Chapter 1 Introduction to MATLABThis book is an Introduction to two subjects:Matlaband numerical first Chapter introducesMatlabby presenting several programs that inves-tigate elementary, but interesting, mathematical problems. If you already havesome experience programming in another language, we hope that you can see howMatlabworks by simply studying these you want a more comprehensive Introduction , there are many resourcesavailable. You can select theHelptab in the toolstrip atop theMatlabcom-mand window, then selectDocumentation,MATLABandGetting MathWorks Web site, MATLAB Tutorials and Learning Resources[11], offersa number of introductory videos and a PDF manual entitledGetting Started Introduction to MATLAB through a collection of mathematical and com-putational projects is provided by Moler s free onlineExperiments with MATLAB [6].

2 A list of over 1500 MATLAB -based books by other authors and publishers, inseveral languages, is available at [12]. Three introductions toMatlabare of par-ticular interest here: a relatively short primer by Sigmon and Davis [9], a medium-sized, mathematically oriented text by Higham and Higham [3], and a large, com-prehensive manual by Hanselman and Littlefield [2].You should have a copy ofMatlabclose at hand so you can run our sampleprograms as you read about them. All of the programs used in this book have beencollected in a directory (or folder) namedNCM(The directory name is the initials of the book title.) You can either startMatlabin this directory or usepathtoolto add the directory to 18, 201312 Chapter 1. Introduction to The Golden RatioWhat is the world s most interesting number?

3 Perhaps you like , ore, or people might vote for , thegolden ratio, computed here by our = (1 + sqrt(5))/2 This producesphi = s see more longphiphi = didn t recompute , it just displayed 16 significant digits instead of golden ratio shows up in many places in mathematics; we ll see severalin this book . The golden ratio gets its name from the golden rectangle, shown inFigure The golden rectangle has the property that removing a square leaves asmaller rectangle with the same shape. 111 Figure golden the aspect ratios of the rectangles gives a defining equation for :1 = equation says that you can compute the reciprocal of by simply subtractingone. How many numbers have that property?Multiplying the aspect ratio equation by produces the polynomial equation 2 1 = The Golden Ratio3 The roots of this equation are given by the quadratic formula: =1 positive root is the golden you have forgotten the quadratic formula, you can askMatlabto findthe roots of the a polynomial by the vector of itscoefficients, in descending order.

4 So the vectorp = [1 -1 -1]represents the polynomialp(x) =x2 x roots are computed by = roots(p)producesr = two numbers are the only numbers whose reciprocal can be computed bysubtracting can use the Symbolic Toolbox, which connectsMatlabto a computeralgebra system, to solve the aspect ratio equation without converting it to a poly-nomial. The equation involves a symbolic variable and a double equals sign. Thesolvefunction finds two xr = solve(1/x == x-1)producesr =5^(1/2)/2 + 1/21/2 - 5^(1/2)/2 Theprettyfunction displays the results in a way that resembles typeset (r)produces+--+| 1/2|| 5|4 Chapter 1. Introduction to MATLAB | ---- + 1/2 || 2||||1/2 ||5 || 1/2 - ---- ||2 |+--+The variableris a vector with two components, the symbolic forms of the twosolutions. You can pick off the first component withphi = r(1)which producesphi =5^(1/2)/2 + 1/2 This expression can be converted to a numerical value in two different ways.

5 It canbe evaluated to any number of digits using variable-precision arithmetic with (phi,50)produces 50 can also be converted to double-precision floating point, which is the principalway thatMatlabrepresents numbers, with = double(phi)producesphi = aspect ratio equation is simple enough to have closed-form symbolic so-lutions. More complicated equations have to be solved approximately. InMatlabananonymous functionis a convenient way to define an object that can be used asan argument to other functions. The statementf = @(x) (x-1)definesf(x) = 1/x (x 1) and producesf =@(x) (x-1)The graph off(x) over the interval 0 x 4 shown in Figure is The Golden 3 2 101234567x1/x (x 1)Figure ( ) = (f,0,4)The nameezplotstands for easy plot, although some of the English-speakingworld would pronounce it e-zed plot.

6 Even thoughf(x) becomes infinite asx!0,ezplotautomatically picks a reasonable vertical statementphi = fzero(f,1)looks for a zero off(x) nearx= 1. It produces an approximation to that isaccurate to almost full precision. The result can be inserted in Figure withhold onplot(phi,0,'o')The followingMatlabprogram produces the picture of the golden rectangleshown in Figure The program is contained in an M-file , soissuing the commandgoldrectruns the script and creates the GOLDRECT Plot the golden rectanglephi = (1+sqrt(5))/2;x = [0 phi phi 0 0];y = [0 0 1 1 0];u = [1 1];v = [0 1];6 Chapter 1. Introduction to MATLAB plot(x,y,'b',u,v,'b--')text(phi/2, ,'\phi')text((1+phi)/2, ,'\phi - 1')text( ,.5,'1')text(.5, ,'1')axis equalaxis offset(gcf,'color','white')The vectorsxandyeach contain five elements.

7 Connecting consecutive(xk, yk) pairs with straight lines produces the outside rectangle. The vectorsuandveach contain two elements. The line connecting (u1, v1) with (u2, v2) sepa-rates the rectangle into the square and the smaller rectangle. Theplotcommanddraws these lines thex ylines in solid blue and theu vline in dashed next four statements place text at various points; the string'nphi'denotes theGreek letter. The twoaxisstatements cause the scaling in thexandydirectionsto be equal and then turn off the display of the axes. The last statement sets thebackground color ofgcf, which stands forget current figure, to fractionis an infinite expression of the forma0+1a1+1a2+1a3+ .If all theak s are equal to 1, the continued fraction is another representation of thegolden ratio: = 1 +11 +11+11+.

8 The followingMatlabfunction generates and evaluates truncated continued frac-tion approximations to . The code is stored in an M-file goldfract(n)%GOLDFRACT Golden ratio continued GOLDFRACT(n) displays n = '1';for k = 1:np = ['1+1/(' p ')'];endpp = 1;q = 1;for k = 1:ns = p;p = p + q;q = s; The Golden Ratio7endp = sprintf('%d/%d',p,q)format longp = eval(p)format shorterr = (1+sqrt(5))/2 - pThe statementgoldfract(6)producesp =1+1/(1+1/(1+1/(1+1/(1+1/(1+1/(1))))))p =21/13p = = threep s are all different representations of the same approximation to .The firstpis the continued fraction truncated to six terms. There are sixright parentheses. Thispis a string generated by starting with a single 1 (that sgoldfract(0)) and repeatedly inserting the string 1+1/( in front and the string ) in back.

9 No matter how long this string becomes, it is a secondpis an ordinary fraction with a single integer numerator anddenominator obtained by collapsing the firstp. The basis for the reformulation is1 +1pq=p+ the iteration starts with11and repeatedly replaces the fractionpqwithp+ statement8 Chapter 1. Introduction to MATLABp = sprintf('%d/%d',p,q)prints the final fraction by formattingpandqas decimal integers and placing a / between thirdpis the same number as the first twop s, but is represented asa conventional decimal expansion, obtained by having theMatlabevalfunctionactually do the division expressed in the final quantityerris the difference betweenpand . With only 6 terms,the approximation is accurate to less than 3 digits. How many terms does it taketo get 10 digits of accuracy?

10 As the number of termsnincreases, the truncated continued fraction generatedbygoldfract(n)theoretically approaches . But limitations on the size of theintegers in the numerator and denominator, as well as roundoff error in the actualfloating-point division, eventually intervene. Exercise asks you to investigatethe limiting accuracy ofgoldfract(n). Fibonacci NumbersLeonardo Pisano Fibonacci was born around 1170 and died around 1250 in Pisain what is now Italy. He traveled extensively in Europe and Northern Africa. Hewrote several mathematical texts that, among other things, introduced Europe tothe Hindu-Arabic notation for numbers. Even though his books had to be tran-scribed by hand, they were widely circulated. In his best known book ,Liber Abaci,published in 1202, he posed the following problem:A man put a pair of rabbits in a place surrounded on all sides by a many pairs of rabbits can be produced from that pair in a year if itis supposed that every month each pair begets a new pair which from thesecond month on becomes productive?


Related search queries