Matlab Examples AE470

download Matlab Examples AE470

of 24

Transcript of Matlab Examples AE470

  • 8/12/2019 Matlab Examples AE470

    1/24

    AE470 Examples of Matlab refreshers

    Problem 1The Taylor series expansion of sin(x) is

    sin x x x

    3

    3!

    x5

    5! x

    7

    7! ...

    Write a code which uses that expression to compute the approximate value of sin(x) for aseries of values of x between 0 and 2 . Find out how many terms are needed for a given valueof x to achieve a certain level of precision (i.e., absolute error). Obtain a single graph thatdisplays for 50 values of x, the number N of terms in the series for 5 values of the precision:10 -6, 10 -8, 10 -10, 10 -12 and 10 -14. Make sure to label the axes and to provide legends for thecurves. Comment on your solution. Try for larger intervals ( 0 to 4 or 6 ): what happens to

    N for the high precision levels for large values of x?

    Solution

    % Program taylor_sin%

    xmax=2*pi; % maximum value of xnum_x=100; % number of x valuesdx=xmax/num_x; % increment in xnum_eps=5; % number of epsilon(tolerance of errors)epsilon=zeros(5,1);epsilon(1)=1.e-06; % specify epsilon valuesepsilon(2)=1.e-08;epsilon(3)=1.e-10;epsilon(4)=1.e-12;epsilon(5)=1.e-14;solution=zeros(num_x,2,num_eps); % prepare solution array to store theresults%for k=1:num_eps % loop for precision values

    for i=1:num_x % loop for x valuesx=i*dx; % current x valuepartial_sum=x; % initial sum of talyor seriesN=1; % initial number of term = 1NNfactorial=1; % initial factorial value

    while abs(partial_sum-sin(x)) > epsilon(k)% loop while the error > specified precision

    N=N+1; % add counterNNfactorial=NNfactorial*(2*N-2)*(2*N-1); % calculate factorialpartial_sum=partial_sum+(-1)^(N-1)*x^(2*N-1)/NNfactorial;

    % add more term to taylor_seriesendsolution(i,1,k)=x; % store current x valuesolution(i,2,k)=N; % store number of terms needed

    endend%% plot and add labels and legend%plot(solution(:,1,1),solution(:,2,1),'b-',solution(:,1,2),solution(:,2,2),'r:',solution(:,1,3),solution(:,2,3),'g-.',solution(:,1,4),solution(:,2,4),'m--',solution(:,1,5),solution(:,2,5),'c-')xlabel('x');ylabel('N');legend('epsilon=1.e-6','epsilon=1.e-8','epsilon=1.e-10','epsilon=1.e-12','epsilon=1.e-14',0);

  • 8/12/2019 Matlab Examples AE470

    2/24

    Comments about the results

    (1) As the value of x increases, the number of terms N required for convergence also increases(Figure 1).

    (2) For a given value of x, the higher the required precision, the higher the number of termsrequired for convergence.

    (3) When the value of x is too high at high level of precision, the significance of numerical

    approximation by series is lost due to the loss of effective digits associated with the ratio ofvery large numbers. (Figure 2)

    Figure 1. Number of terms N needed for convergence as a function of x for various values of theconvergence parameter epsilon ( x = 0 to 2 ! ).

  • 8/12/2019 Matlab Examples AE470

    3/24

    Figure 2. Same as Figure 1 but for wider range of x ( x = 0 to 4 ! ).

  • 8/12/2019 Matlab Examples AE470

    4/24

    Problem 2.The Taylor series expansion of log(1+x) = x - ( 1 / 2)x

    2 + ( 1 / 3)x3 - (1 / 4)x

    4 for -1< x

  • 8/12/2019 Matlab Examples AE470

    5/24

  • 8/12/2019 Matlab Examples AE470

    6/24

    Problem 3The Taylor series expansion of sinh(x) is

    sinh x( ) = x + x

    3

    3!+

    x5

    5!+

    x7

    7!+ ....

    Write a Matlab code which uses that expression to compute the approximate value of sinh(x)

    for a given value of x. Stop the series when the approximate value is within 0.001% of theexact value (obtained with sinh(x)). For a given value of x introduced interactively, outputon the screen

    x =

    exact value of sinh x( ) =

    approximate value of sinh x( ) =

    number of terms in approximation =

    Then write a second version of your code that loops over N equally spaced values of x between x min and x max (with N , x min and x max introduced interactively by the user) and creates a plotwith the number of terms in the approximation (to achieve 0.001% precision) as a function of

    x. Then run your code for x min = 1.0 , x max = 30.0 and N = 100. Comment on your solution.

    Solution The basic structure of the two codes is relatively self-explanatory.

    Here is the first code sinhcode1.m and a typical output

    % Computes the Taylor series approximation of sinh(x) for a% user-introduced value of x within a given precision%TargetPrecision=0.001; % precision in percentMaxNumTerm=100; % maximum number of terms in Taylor seriesx=input(' Enter the value of the argument x = ')ExactValue=sinh(x); % exact value of sinh(x)PartialSum=0; % partial value of the seriesICounter=0; % number of terms in the series

    while 100*abs(ExactValue-PartialSum)/ExactValue > TargetPrecision % check for% convergence

    ICounter=ICounter+1; % if no convergence, add one term to the seriesPartialSum=PartialSum+(x^(2*ICounter-1))/factorial(2*ICounter-1);if ICounter > MaxNumTerm % check for lack of convergence

    sprintf( ' No convergence achieved after %d terms forx=%d\n',ICounter,xx)

    breakend

    endsprintf(' x = %15.10f\n',x) % output results as specified in assignmentsprintf(' exact value of sinh(x) = %15.10f\n',ExactValue)sprintf(' approximate value of sinh(x) = %15.10f\n',PartialSum)sprintf(' number of terms in approximation = %d\n',ICounter)

    >> sinhcode1Enter the value of the argument x = 10.5

    ans =x = 10.5000000000

  • 8/12/2019 Matlab Examples AE470

    7/24

    ans =exact value of sinh(x) = 18157.7513233551ans =approximate value of sinh(x) = 18157.6986168544ans =number of terms in approximation = 14

    The second code sinhcode2.m just adds a loop (over the values of x) around the first one:

    % AE 470 - Programming assignment # 1 - Problem 1 - Code 2% Computes the Taylor series approximation of sinh(x) for a% user-introduced value of x within a given precision.% Plots the number of terms needed for convergence as a function% of x between xmin and xmax%TargetPrecision=0.001; % precision in percentMaxNumTerm=100; % maximum number of terms in Taylor seriesxmin=input(' Enter minimum value of the argument xmin = ')xmax=input(' Enter maximum value of the argument xmax = ')NumXValues=input(' Enter the number of x values NumXValues = ')x=linspace(xmin,xmax,NumXValues); % vector with equally spaced NumXValues

    values of argument xNumTerm=zeros(NumXValues,1); % vector with number of terms forconvergencefor k=1:NumXValues % loop over x values

    xx=x(k);ExactValue=sinh(xx); % exact value of sinh(x)PartialSum=0; % partial value of the seriesICounter=0; % number of terms in the series

    while 100*abs(ExactValue-PartialSum)/ExactValue > TargetPrecision % checkfor

    %convergenceICounter=ICounter+1; % if no convergence, add one term to the seriesPartialSum=PartialSum+(xx^(2*ICounter-1))/factorial(2*ICounter-1);if ICounter > MaxNumTerm % check for lack of convergence

    sprintf('No convergence achieved after %d terms for x =%d\n',ICounter,xx)break

    endendNumTerm(k)=ICounter; % store the number of terms in vector NumTerm (for

    future% display)

    endplot(x,NumTerm,'b-o') % display results with solid blue line with circularsymbolsxlabel('x'); % label for x axisylabel('Number of terms in Taylor series'); % label for y axistitle(strcat('Precision = ',num2str(TargetPrecision,'%f'),' percent')); %title

    %for the plot

  • 8/12/2019 Matlab Examples AE470

    8/24

    The output of the code is shown in Figure 1.

    Figure 1. x-dependence of the number of terms needed to achieve convergence (within 0.001%) inthe Taylor series expansion of sinh( x).

    As apparent there, an increasing number of terms are needed to capture sinh( x) accurately as x increases, although that increases in less than linear.

  • 8/12/2019 Matlab Examples AE470

    9/24

    Problem 4. Write a simple Matlab code that, given an integer number N between 1 and 100,computes the ratio

    q N ( ) =i

    2

    i = 1

    N

    !

    i3

    i = 1

    N

    !.

    Output the result on the screen as User input N = Computed ratio q(N) =

    Key Matlab commands: input , for , sprintf

    Solution Code HW1_Problem1_solution.m

    % This code will, given an integer number N between 1 and 100, % compute the ratio of the sum of the squares and the sum of the cubes

    % of the summation index "i" from 1 to N % ============Definition of Variables============ % N = upper limit of summation % i = summation index % num = numerator of ratio % den = denominator of ratio % q = value of ratio, q(N) % ===============================================

    N=input( 'Enter N: ' ); % Request upper limit of summation, N

    if (N>=1 & N> HW1_Problem1_solutionEnter N: 36User input N = 36Computed ratio q(N) = 0.036537>> HW1_Problem1_solutionEnter N: 47User input N = 47

  • 8/12/2019 Matlab Examples AE470

    10/24

    Computed ratio q(N) = 0.028073

  • 8/12/2019 Matlab Examples AE470

    11/24

    Problem 5. As you probably know, the Fibonacci numbers P i i = 1,2,...( ) are obtained bystarting with 0 and 1, and then adding the last two numbers to obtain the next one.

    0 1 1 2 3 5 8 13 21 34 Display the first 50 numbers on the screen and plot the ratio of two successive numbers( P i + 1 / P i ) for i = 2,...,50 and show graphically that it tends to a limit (sometimes referred to asthe Golden Ratio).

    Key Matlab command: plot, title

    Solution Code HW1_Problem2_solution.m

    % This code will display the first 50 Fibonacci numbers on the screen% and plot the ratio of two successive numbers (Pi+1 / Pi) for % i = 2,...,50 and will show graphically that it tends to a% limit (sometimes referred to as the Golden Ratio).

    % ============Definition of Variables============ % i = index for Fibonacci number % ii = auxillary array for plotting

    % P(i) = Fibonacci number % ratio = (Pi+1 / Pi)= Fibonacci number ratio % =============================================== NumTerms=50; % number of terms in Fibonacci number series P = zeros(1,NumTerms); % initialize row matrix to contain first 50 Fibonaccinumbers P(1)=0; % first element is zeroP(2)=1; % second element is one for i=3:NumTerms % for-loop to find the rest of the Fibonacci numbers

    P(i)=P(i-1)+P(i-2);end

    fprintf( 'First %i Fibonacci numbers are: \n' ,NumTerms)for i=1:NumTerms % display first NumTerms numbers on the screen

    fprintf( 'P(%i)= %i\n' ,i,P(i))end

    for i=2:NumTerms-1 % for-loop to compute ratio (Pi+1 / Pi)ratio(i) = P(i+1)/P(i);

    end

    ii = linspace(2,NumTerms,NumTerms-1); % create linear array for x-axis withsame number of elements as ratio(i)plot(ii,ratio) % create plot, title, and axes title( 'Aaron Shinn - Fibonacci numbers - Plot of P(i+1)/P(i) versus i' )xlabel( 'i' )ylabel( 'P(i+1)/P(i)' )

    Screen output >> HW1_Problem2_solutionFirst 50 Fibonacci numbers are:P(1)= 0P(2)= 1P(3)= 1P(4)= 2P(5)= 3P(6)= 5P(7)= 8P(8)= 13P(9)= 21

  • 8/12/2019 Matlab Examples AE470

    12/24

    P(10)= 34P(11)= 55P(12)= 89P(13)= 144P(14)= 233P(15)= 377P(16)= 610P(17)= 987P(18)= 1597

    P(19)= 2584P(20)= 4181P(21)= 6765P(22)= 10946P(23)= 17711P(24)= 28657P(25)= 46368P(26)= 75025P(27)= 121393P(28)= 196418P(29)= 317811P(30)= 514229P(31)= 832040P(32)= 1346269

    P(33)= 2178309P(34)= 3524578P(35)= 5702887P(36)= 9227465P(37)= 14930352P(38)= 24157817P(39)= 39088169P(40)= 63245986P(41)= 102334155P(42)= 165580141P(43)= 267914296P(44)= 433494437P(45)= 701408733P(46)= 1134903170

    P(47)= 1836311903P(48)= 2.971215e+09P(49)= 4.807527e+09P(50)= 7.778742e+09

    The ratio of successive Fibonacci numbers is shown in the figure below, showing how quickly itconverges to a value close to 1.6.

  • 8/12/2019 Matlab Examples AE470

    13/24

    Ratio of successive Fibonacci numbers.

  • 8/12/2019 Matlab Examples AE470

    14/24

    Problem 6. Create an array A N , N ( ) where N being a user-defined integer between 1 and 20(and introduced interactively), with

    A i, j ( ) = i2 + j .Compute and output on the screen the N eigenvalues of the matrix A .

    Key Matlab commands: zeros , eig

    Solution Code HW1-Problem3_solution.m

    % This code will Create an array A(N,N) where N is% a user-defined integer between 1 and 20 % (and introduced interactively), with A(i,j)=sqrt(i^2+j) % Compute and output on the screen the N eigenvalues of the matrix A.

    % ============Definition of Variables============ % N = user-defined integer between 1 and 20 % i,j = indices for row and column % A(i,j) = main array % E = array containing the N eigenvalues of A(i,j) % ===============================================

    N=input( 'Enter N: ' ); % Request user-defined integer between 1 and 20 A=zeros(N,N); % initialize A

    if (N>=1 & N

  • 8/12/2019 Matlab Examples AE470

    15/24

    Problem 7. Write a Matlab code that uses a Monte-Carlo method to compute the value of ! .Consider the figure made of a quarter circle (of radius 1) inscribed in a square (of size 1). Theratio of the area of region A to that of the square is given by ! / 4 .

    Using a random number generator, pick randomly N pointswithin the square (defined by 0 ! x ! 1 and 0 ! y ! 1 ) andcompute the number of times P the points fall into region A .

    Then plot the probability of successful hits (i.e., P/N ) as afunction of N for N = 1 to 10,000. Normalize your y-axis by! / 4 and comment on your solution.

    Key Matlab command: rand, if

    Solution Code HW1_Poblem4_solution.m

    % Write a Matlab code that uses a Monte-Carlo method to% compute the value of pi. Using a random number generator % pick randomly N points within the square (defined by % 0

  • 8/12/2019 Matlab Examples AE470

    16/24

    title xlabel( 'N' ),ylabel( 'Normalized Probability' ) % set-up axis titles

    As shown in the figure above, the Monte-Carlo approximation of ! quickly converges: after 2000

    attempts, the probability of falling into the quarter circle approaches!

    /4 . The figure below showsthe initial phase of the convergence process.

  • 8/12/2019 Matlab Examples AE470

    17/24

  • 8/12/2019 Matlab Examples AE470

    18/24

    Problem 8. Create a data file (called mydata.dat) with 14 data points (characterized by x , y( ) coordinates with 0 ! x ! 10 and ! 5 " y " 10 . Create these data points by hand using yourfavorite editor (the simplest way is to use that available in Matlab to create .m files). Thenwrite a code that (i) open the data file, (ii) read the 14 data points, (iii) uses the commandpolyfit to find the 4 coefficients of the 3 rd -order polynomial fit that best passes among the 14points. Output the 4 coefficients on the screen (indicating on your screen display which onecorresponds to the cubic term, the quadratic term ). Then plot the 14 points (as symbols)

    and the polynomial fit (as solid curve).

    Key Matlab commands: load , polyfit , polyval , linspace

    Solution code

    % Least square polynomial fit of 14 data points (stored in file 'prog5.dat') %% This code computes and displays the 3rd-order polynomial fit for 14 data % points stored in a file 'prog5.daa' % % read from file 'prog5.dat' % XYarray=load( 'prog5.dat' );NumPoints=size(XYarray,1) % number of data points % % Use polyfit command to compute the four coefficients of the 3rd order % polynomial fit Coeff=polyfit(XYarray(:,1),XYarray(:,2),3);fprintf( ' Coefficients of 3rd order polynomial fit:P(1)*x^3+p(2)*x^2+P(3)*x+P(4) \n' )fprintf( ' P(1) = %d \n' ,Coeff(1))fprintf( ' P(2) = %d \n' ,Coeff(2))fprintf( ' P(3) = %d \n' ,Coeff(3))fprintf( ' P(4) = %d \n' ,Coeff(4))% % display the data points and the polynomial fir using command polyval xx=linspace(min(XYarray(:,1)),max(XYarray(:,1)),100); % set 100 points forpolynomial display yy=polyval(Coeff,xx); % compute y-valuesplot(XYarray(:,1),XYarray(:,2), 'ro' ,xx,yy, 'b-' , 'linewidth' ,2)xlabel( 'x' );ylabel( 'y' );title( 'Philippe Geubelle - 3rd order polynomial fit of 14 data points' );

    Data points (File prog5.dat)

    0.0 10.00.3 8.01.2 5.02.5 -1.02.9 -1.53.2 -1.43.9 -0.25.6 1.36.5 2.47.0 2.87.5 3.1

  • 8/12/2019 Matlab Examples AE470

    19/24

    8.0 3.08.7 2.89.2 2.5

    Screen output prog5NumPoints =

    14

    Coefficients of 3rd order polynomial fit P(1)*x^3+p(2)*x^2+P(3)*x+P(4)P(1) = -9.140170e-02P(2) = 1.574714e+00P(3) = -7.632546e+00P(4) = 1.038157e+01

    Resulting plot

    3rd-order polynomial fit (solid curve) of 14 data points (shown as symbols).

  • 8/12/2019 Matlab Examples AE470

    20/24

    Problem 9. The Taylor series expansion for cos(x) is

    cos x ( ) = 1 ! x

    2

    2!+

    x 4

    4!! x

    6

    6!+ ...

    For 50 values of x equally spaced between x = 0 and x = ! / 4 , compute the number of terms N(x) needed in the Taylor series expansion to achieve a precision of 10

    ! 6. Plot N(x) versus x

    and comment on your solution.

    Solution

    Code

    % Taylor series expansion of cos(x) %% This code computes the number of terms N(x) needed in the Taylor % series expansion of cos(x) to achieve a given precision. % Then plot N(x) versus x. % NumXValues=50; % number of X values (equally spaced between 0 and pi/4) XValues=linspace(0,pi/4,NumXValues); % vector of X values between 0 and Pi/4 NumTerms=zeros(NumXValues,1); % solution vector with N(x) Tolerance=1.e-06; % Tolerancefor i=1:NumXValues % loop over X values

    X=XValues(i); % current value of X CosExact=cos(X); % exact value of cos(X) SumCos=1; % Initiate Taylor series expansion at X NumTerms(i)=1; % Initiate N(x) to 1

    while abs(CosExact-SumCos)>ToleranceNumTerms(i)=NumTerms(i)+1; % increment N(x) jaux=NumTerms(i)-1; % auxiliary index SumCos=SumCos+(-1)^(jaux)*(X^(2*jaux))/factorial(2*jaux); % add term to

    Taylor series expansion end

    end plot(XValues,NumTerms, 'b-o' , 'linewidth' ,2) % plot N(x) versus x title( ' Philippe Geubelle - Taylor series expansion of cos(x)' );xlabel( 'X' );ylabel( 'N(X)' );

    The variation of N(x) is shown in the figure below, showing that, as x increases, the number ofterms needed in the Taylor series expansion to achieve the prescribed precision increases from 1 (at

    x=0 ) to 5 (for x approaching ! /4 ).

  • 8/12/2019 Matlab Examples AE470

    21/24

    Variation of N(x) versus x for the Taylor series expansion of cos(x) .

  • 8/12/2019 Matlab Examples AE470

    22/24

    Problem 10. The central difference approximation of the first derivative f ' x( ) of a function f x( ) is

    f ' x( ) = f x+ ! x( )" f x" ! x( )

    2 ! x+ O ! x

    2( ),where ! x is a small increment in x. Write a Matlab code that computes f ' 0.5( ) for f x( ) = sin x( ) and g ' 1( ) for g x( ) = exp x 2( ). A function call should be used whenever thefunction f or g is to be evaluated.Let us define the relative error as

    ! " x; a( ) = 100* f 'exact a( )# f 'numer a ," x( )

    f 'exact a( ).

    Plot on a log-log plot the ! x dependence of ! " x ; a( ) for the two requested derivatives for10 ! 8 " x " 10

    0. Does the slope correspond to your expectation? What happens when ! x

    becomes very small?

    Key Matlab commands: logspace , loglog , function .

    Solution

    Here is the code prog7.m for the second function g(x) .

    % Central difference approximation of first derivative %% This code computes the central difference approximation of the firstderivative% f'(x)=(f(x+dx)-f(x-dx))/2dx % and investigates the dependence of the numerical approximation on dx % LogdxMin=-8;LogdxMax=0;

    NumdxValues=50; % number of dx values (equally spaced on log scale between10^LogdxMin% and 10^LogdxMax) dxValues=logspace(LogdxMin,LogdxMax,NumdxValues); % create dx values fperror=zeros(NumdxValues,1); % solution vector with relative error onderivative xvalue=1.0; % value of x at which the derivative is to be computed fpexact=2*xvalue*exp(xvalue^2); % exact value of the derivative of sin(x) for i=1:NumdxValues % loop over X values

    dx=dxValues(i); % current value of X fpnumer=(func7(xvalue+dx)-func7(xvalue-dx))/(2*dx); % central difference

    approximation of derivative fperror(i)=100*abs((fpnumer-fpexact)/fpexact); % error

    end loglog(dxValues,fperror, 'b-o' , 'linewidth' ,2) % log-log plot of error versus dx title( ' Philippe Geubelle - Central difference approximation of firstderivative' );xlabel( 'dx' );ylabel( 'relative error (in %)' );grid on ;The associated subroutine func7.m is as follows:

    function ff=func7(x)% function subroutine that computes the function used in problem 7 ff=exp(x^2);

  • 8/12/2019 Matlab Examples AE470

    23/24

    The two graphs are shown below.

    Central difference approximation of f(0.5) where f(x)=sin(x) .

  • 8/12/2019 Matlab Examples AE470

    24/24

    Central difference approximation of g(1) where g(x)=exp(x^2) .

    In both cases, the slope of the error curve is 2, indicating that the central difference approximationof the first derivative is of second order (i.e., decreasing dx by a factor of 2 decreases the error on

    the derivative by a factor of 4). When the value of dx becomes very small (less than 10^-5), thenumerical solution suffers from round-off errors, as the approximation of the derivative is obtainedby the ratio of two very small numbers.