Sunday, February 24, 2013

MATLAB - Simpson's Rule

simpson13
% ========================================================================
% ***************** Integration by Simpson's 1/3 method ******************
% *************************** By Mahesha MG ******************************
% Date: 23/02/2013
% ========================================================================
display('Equation is x^2+x-2')
xl=input('Enter lower limit:');
xu=input('Enter upper upper limit: ');
n=input('Enter number of subintervals: ');
% ========================================================================
h=(xu-xl)/n;
x=xl+h;
integ=equan(xl)+equan(xu);
i=1;
while (x<xu)
    if i
        integ=integ+4*equan(x);
        i=0;
    else
        integ=integ+2*equan(x);
        i=1;
    end
    x=x+h;
end
integ=integ*h/3
% ========================================================================
% Equation to be solved
function[eqn]=equan(x);
eqn=x^2+x-2;

3 comments:

  1. Acho que há um erro nesse código.
    A condição do while está rodando uma vez mais do que o necessário, quando eu executei aqui em casa não funcionou.
    Para concertar o problema, fiz o seguinte:
    "while (x<xu-h)
    [...]
    end"

    I think there is an error in that code.
    The condition of the while running once more than necessary when I performed here at home did not work.
    To fix the problem, I did the following:
    "while (x <xu-h)
        [...]
    end "

    ReplyDelete
    Replies
    1. Can you give me the inputs that you have given?
      In Simpson's rule, number of subintervals should be even.
      If you take
      "while (x <xu-h)
      [...]
      end "
      then I think one point will miss ie "x-h".

      Delete