Tuesday, July 31, 2012

MATLAB - Bisection Method


bisection

% ****** To find root of given equation by bisection method ******
% ********************** By Mahesha MG ***************************
display('Equation is x^2+x-2 = 0')
i=1;
while(i)

     xl=input('Enter lower value:');
     xu=input('Enter upper value: ');
     e=input('Enter accuracy: ');
    if equan(xl)*equan(xu)<0
        i=0;
    else
        warning('Enter proper range');
    end

end
if equan(xl)<0
    xn=xl;
    xp=xu;
else
    xn=xu;
    xp=xl;
end
while (abs(xn-xp)>e)
    xm=(xn+xp)/2;
    if equan(xm)<0
        xn=xm;
    else

        xp=xm;
    end
end
Root=xm
Equation is x^2+x-2 = 0

Enter lower value:3
Enter upper value: 5
Enter accuracy: .0001
Warning: Enter proper range 
> In bisection at 12 
Enter lower value:0
Enter upper value: 3
Enter accuracy: .0001
Root =

    1.0000

% Equation to be solved
function[eqn]=equan(x);
eqn=x^2+x-2;

9 comments:

  1. WHEn i copy your code..it is working until i enter the accuracy

    ??? Undefined function or method 'equan' for input arguments of type 'double'.

    Error in ==> b at 8
    if equan(xl)*equan(xu)<0

    this was the message...cn you fix it????thanks..

    ReplyDelete
    Replies
    1. Hi
      here in the program, function whose root is to be obtained is stored in another file with name "equan.m"
      So create new .m file named equan and write following lines in that and save.

      % Equation to be solved
      function[eqn]=equan(x);
      eqn=x^2+x-2;

      Now run bisection program. It should work.

      Delete
  2. oh...its finally wotking..thank you very much..^_^

    can i ask do you have newton-raphson code for matlab??

    ReplyDelete
    Replies
    1. http://numericalcomputation.blogspot.in/2013/03/matlab-newton-raphson-method.html

      Delete
  3. last question can i usea nother equation using this code.. ??

    x^3+x^2-3x-3 and
    x^3-3x^2-6x+8

    ReplyDelete
    Replies
    1. definitely. you have to put the required equation in equan.m file

      Delete
  4. Hi, i'am doing a program similar to this but the input will be an equation and the xl and xu will be generated by the program. Do you have any algorithms? I really need your help. Thanks!

    ReplyDelete
  5. Hi, I'm doing a program similar to this but the input will be an equation and the xl and xu will be generated by the program. Is there any algorithms you can suggest on how my program will generate the right xl and xu? Thanks!

    ReplyDelete
    Replies
    1. http://numericalcomputation.blogspot.in/2013/10/matlab-bisection-new.html

      Delete