numerical approaches via matlab

Upload: kassaphysics

Post on 30-May-2018

240 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Numerical Approaches via MATLAB

    1/23

    Numerical Approaches Via MATLABNumerical Approaches Via MATLABTutorial on Computational Physics I (Phys.605)

    Tsegaye Kassa

    Department of Physics, Graduate Studies

    Bahir Dar University, Bahir Dar, Ethiopia

    E-mail:[email protected]

    May 2008

    Bahir Dar

  • 8/14/2019 Numerical Approaches via MATLAB

    2/23

    OutlineOutline

    Numerical Derivatives

    Numerical Integrations

    Ordinary Differential Equations

  • 8/14/2019 Numerical Approaches via MATLAB

    3/23

    Numerical DerivativesNumerical Derivatives

    % This program calculates the derivatives of 10+78x^2 at

    any point you choose.

    x=input('Enter the value of x that you want to calculate derivatives')

    h=input('choose the step you want to use')

    res=(neja_fun(x+h)-neja_fun(x))/h

    % This function is developed to calculate the first derivative of a functionfunction[y]=neja_fun(x)

    y=10+78*x^2;

    Forward Derivative Formula

  • 8/14/2019 Numerical Approaches via MATLAB

    4/23

    Comparison of Numerical and AnalyticalComparison of Numerical and AnalyticalSolutionsSolutions

    %tsegaye-program to compute the Numerical Derivatives of the function

    %and compare with the exact valuesclear; help tsegaye % clear memory and print header

    x=input('Enter the location(x)-');

    h=input('choose the step that want to use')

    for i=1:3

    hplot(i)=h; %record the value of h for plotting

    %Right and Centered first derivativesresR(i)=(neja_fund(x+h)-neja_fund(x))/h;

    resC(i)=(neja_fund(x+h)-(neja_fund(x-h)))/2*h;

    % The Exact first derivativeresT(i)=neja_fund(x);

    h=h/2; % halve the grid spacing at each iteration

    end

    %Plot numerical and true derivation on semilog scale

    semilogx(hplot,resR,'+', hplot,resC,'g:', hplot,resT,'r-')

    xlabel('interval size(h)')ylabel('First derivative')

    legend('Right derivative', 'Centered derivative','Exact derivative')

    title('Comparison of forward, centered and Exact derivatives')

    %Displaying Outputs

    fprintf('The value of right derivative=%g\n',resR)

    printf('The value of centered derivative=%g\n',resC)

    fprintf('The value ofexact derivative=%g\n',resR)

    function[y]=neja_fund(x)

    y=78*x^2+10;

  • 8/14/2019 Numerical Approaches via MATLAB

    5/23

    ContC

    ontHigher Order Derivative

    % This program is developed to calculate the Second Derivative of e^x% at x=15.

    x=input('Enter the value of x that you want to use')h=input('choose the step you want to use')

    res=(neja_fun2(x+h)+neja_fun2(x-h)-(2)*neja_fun2(x))/h^2

    % fprintf('The second derivative of the function is %f\n',res)

    % This is a function developed to estimate the second derivative of the function.

    function[y]= neja_fun2(x)

    y=exp(x);

  • 8/14/2019 Numerical Approaches via MATLAB

    6/23

    Numerical IntegrationNumerical Integration

    RectangularRule

    % This program is developed to calculate the integral of x^2 at any

    % point you choose.

    a=input('Enter the value of a')b=input('Enter the value of b')

    dx=input('choose the step dx')

    n=b-a/dx;

    sum=0; % Initialization

    for i=1:nsum=sum+neja_fun3(a+(i-1)*dx)*dx % Left rectangular rule.

    end

    % This function is develped to calcualate the integral of y=x^2

    function[y]= neja_fun3(x)

    y=x^2;

  • 8/14/2019 Numerical Approaches via MATLAB

    7/23

    ContCont

    Trapezoidal

    Rule

    help Integration ;%clear memory and print the headerfor x=0:0.5:2

    f='78*x^2+10';

    h=0.5;

    fo=subs(f,'0','x');

    eval(fo);

    f1=subs(f,'0.5','x');

    eval(f1);

    f2=subs(f,'1','x');eval(f2);

    f3=subs(f,'1.5','x');

    eval(f3);

    f4=subs(f,'2','x');

    eval(f4);

    f='78*x^2+10' ; %creates symbollic function

    Iexact=int(f,0,2); %computes the exact value of the integration with limit of integration 0 and 2.

    d=eval(Iexact);Iestim=h/2*(fo+2*f1+2*f2+2*f3+f4); %estimates the integration with in the given interval

    e=eval(Iestim);

    end

    fprintf('The Analytical Soluion of the Integral is=%f\n',d)

    fprintf('The Trapizoidal Estimate of the Integral is=%f\n',e)

  • 8/14/2019 Numerical Approaches via MATLAB

    8/23

  • 8/14/2019 Numerical Approaches via MATLAB

    9/23

    O

    rdinary Differential EquationsO

    rdinary Differential EquationsEuler forward Method

    %A program that computes second order ode given by

    %using four alternative numerical methods.

    clear global; help Numerical_methods;y(1)=1; x(1)=2;

    h=0.1;

    t=0:h:5;

    for i=1:length(t)-1

    y(i+1) = y(i)+h*x(i);x(i+1) = x(i)+4*h*y(i);

    end

    yexact=exp(2*t);

    plot(t,y,'-b',t,yexact,'-g')

    y"-4y=0

  • 8/14/2019 Numerical Approaches via MATLAB

    10/23

    ContC

    onthold on

    for i=1:length(t)-1

    xm(i+1) = x(i);

    y(i+1) = y(i)+h/2*(x(i)+xm(i+1));

    x(i+1) = x(i)+2*h*((y(i)+y(i+1)));

    while abs(x(i+1)-xm(i+1))>0.001

    x(i+1) = x(i)+2*h*((y(i)+y(i+1)));

    xm(i+1) = x(i+1);

    end

    end

    plot(t,y,'-r')

    Euler Modified Method

  • 8/14/2019 Numerical Approaches via MATLAB

    11/23

    ContC

    onthold on

    for i=1:length(t)-1

    k1 = h*x(i);m1 = 4*h*y(i);

    k2 = h*(x(i)+m1);

    m2 = 4*h*(y(i)+k1);

    y(i+1) = y(i)+0.5*(k1+k2);

    x(i+1) = x(i)+0.5*(m1+m2);end

    plot(t,y,':y')

    Second - Order Runge Kutta Method

  • 8/14/2019 Numerical Approaches via MATLAB

    12/23

    ContC

    ontThird - Order Runge Kutta Methodhold on

    for i=1:length(t)-1

    k1 = h*x(i);

    m1 = 4*h*y(i);

    k2 = h*(x(i)+m1/2);

    m2 = 4*h*(y(i)+k1/2);

    k3 = h*(x(i)-m1+2*m2);

    m3= 4*h*(y(i)-k1+2*k2);y(i+1) = y(i)+1/6*(k1+4*k2+k3);

    x(i+1) = x(i)+1/6*(m1+4*m2+m3);

    end

    plot(t,y,':r')

  • 8/14/2019 Numerical Approaches via MATLAB

    13/23

    ContC

    ontFourth - Order Runge Kutta Methodhold on

    for i=1:length(t)-1

    k1 = h*x(i);

    m1 = 4*h*y(i);k2 = h*(x(i)+m1/2);

    m2 = 4*h*(y(i)+k1/2);

    k3 = h*(x(i)+m2/2);

    m3= 4*h*(y(i)+k2/2);

    k4 = h*(x(i)+m3);

    m4= 4*h*(y(i)+k3);

    y(i+1)=y(i)+1/6*(k1+2*(k2+k3)+k4);

    x(i+1)=x(i)+1/6*(m1+2*(m2+m3)+m4);

    end

    plot(t,y,':b')

  • 8/14/2019 Numerical Approaches via MATLAB

    14/23

    ContC

    ontxlabel('Time(sec)')

    ylabel('y(m)')

    title('Comparison of Different Numerical Methods')

    legend('Euler forward','Analytical','Euler modified','Second-order R-K','Third-order R-K','Fourth order R-K')

  • 8/14/2019 Numerical Approaches via MATLAB

    15/23

    Simple PendulumSimple Pendulumclear all; clc; clf;L=10; g=9.8; T=2*pi*sqrt(L/g);

    h=0.04; theta(1)=0.5*pi;

    w(1)=0;t=0:100*T;

    for i=1:length(t)-1

    k1=h*w(i);m1=-h*(g/L)*sin(theta(i));

    k2=h*(w(i)+(m1)/2);

    m2=-h*(g/L)*(sin(theta(i))+(k1)/2);

    k3=h*(w(i)+(m2)/2);

    m3=-h*(g/L)*(sin(theta(i))+(k2)/2);

    k4=h*(w(i)+m3);

    m4=-h*(g/L)*(sin(theta(i))+k3);

    theta(i+1)=theta(i)+1/6*(k1+2*(k2+k3)+k4);

    w(i+1)=w(i)+1/6*(m1+2*(m2+m3)+m4);

    end

    U

    +(L/g)sin(U

    )=0

    Equation of Motion

  • 8/14/2019 Numerical Approaches via MATLAB

    16/23

    Spectral AnalysisSpectral Analysis% Calculate data

    f1=input

    f2=input

    t=

    x = sin(2*pi*f1*t) +sin(2*pi*f2*t)+ 2*randn(size(t));

    y = fft(x); %%Taking the 512-point fast Fourier transform (FFT): y = fft(x,512);

    %m = y.*conj(y)/512; %%The power spectrum, a measurement of the power

    at various frequencies, is m = y.* conj(y) / 512;

    %f = 1000*(0:256)/512;; %%The data sampled at 1000 Hz.

    f = (0:length(y)-1)'*100/length(y);;

    K=abs(y);

    p=unwrap(angle(y));

  • 8/14/2019 Numerical Approaches via MATLAB

    17/23

    ContCont

    % Create time plot

    plot(t,x)

    xlabel('Time (Seconds)')

    legend('Time Series (Unfiltered)')

    title('sin(2*pi*f1*t) +sin(2*pi*f2*t)+ 2*randn(size(t))','fontsize',12.2)

    %title('Time Plot of sin(2*pi*f1*t) + sin(2*pi*f2*t)')

    grid on

    % Create frequency plot

    plot(f,K)

  • 8/14/2019 Numerical Approaches via MATLAB

    18/23

    ContC

    ontxlabel('Frequency (Hz)')

    legend('Frequency Series (Unfiltered)')

    %title('Frequency Plot of sin(2*pi*f1*t) + sin(2*pi*f2*t)')

    grid on

    %Creat frequency plot of noise free wavex = sin(2*pi*f1*t) +sin(2*pi*f2*t);

    y = fft(x);

    m = y.*conj(y)/512;

    K=abs(y);

    %f = 1000*(0:256)/512;; %

    f = (0:length(y)-1)'*100/length(y);;

    plot(f,K)

    xlabel('Frequency (Hz)')

    %title('Frequency Plot of sin(2*pi*f1*t) + sin(2*pi*f2*t)')

    legend('Frequency Series (Filtered)')

  • 8/14/2019 Numerical Approaches via MATLAB

    19/23

    ContC

    ontx = sin(2*pi*f1*t) +sin(2*pi*f2*t);

    y = fft(x,512); %%Taking the 512-point fast Fourier transform (FFT): y = fft(x,512);

    m = y.*conj(y)/512; %%The power spectrum, a measurement of the power at

    various frequencies, is m = y.* conj(y) / 512;

    f = (0:length(y)-1)'*100/length(y);; %%The data sampled at 1000 Hz.%f = 1000*(0:256)/512;; %

    p=unwrap(angle(y));

    % Create time plot

    plot(f,p*180/pi)

    legend('Phase Angle (Filtered)')

  • 8/14/2019 Numerical Approaches via MATLAB

    20/23

    InterpolationInterpolationLinear Interpolation 1%This program is developed to determine the missed data point in a given

    %data points by using linear interpolation.

    clear; help linear; %clear memory and print the header

    x=input('Enter the value of x')

    datax=[1 3 4 6];

    datay=[3 9 12 18];

    if x>=1 & x

  • 8/14/2019 Numerical Approaches via MATLAB

    21/23

    ContC

    ontLinear Interpolation 2

    %This program is developed to determine the missed data point in a given

    %data points by using linear interpolation.

    x=input('Enter the value of x')

    datax=[0,20];datay=[10,50];

    if x>=0 & x

  • 8/14/2019 Numerical Approaches via MATLAB

    22/23

    Interpolation and Extrapolation of ln2Interpolation and Extrapolation of ln2% Interpolation and Extrapolation-This program is developed to %determine the missed

    data point by using interpolation and %extrapolation between the given functionclear;help Interpolation and extrapolation;

    datax=[1 4];

    datay=[0 1.386294];

    x=input('Enter the value of x that you choose')

    if x>=1 & x

  • 8/14/2019 Numerical Approaches via MATLAB

    23/23

    ContCont

    % Extrapolate

    datax=[1 4]

    datay=[0 1.386294]

    x=input('Enter the value of x that you choose')

    if x=4z=datay(1)+(x-datax(1))*(datay(2)-datay(1))/(datax(2)-datax(1))

    end

    datay=exp(datax);

    subplot(212)

    plot(datax,datay,'o-', x,z,'*r')xlabel('Dependant variabel')

    ylabel('Independent variabel')

    title('The first order Lagrange extrapolation')