0

I'm trying to use the bisection method in Matlab to find the root of an equation as q varies from 2000-3000 in 10 step intervals. My code however does not print out a graph even though I have a plot statement and I think it creates an infinite loop since when I run it matlab says busy and I can't close the program unless I force close. I can't see anything in my code that would cause this though, could someone help me out?

function myFunction

a = 20;
b = 40;
tol = 1e-4;
q = 2000:10:3000;
t = zeros(101,1);

for i=(1:length(q))
    f = @(x) (((1800).*log((160000)./(160000 - (x.*q(i)))) - (9.812).*x)./750) - 1;
    t(i) = bisect(f,a,b,tol);
end

figure(1)
plot(q,t)

    function c=bisect(f,a,b,tol)
        k=0;
        while b-a > tol
            c = (a-b)/2;
            if sign(f(c)) == sign(f(b))
                b=c;
            else
                a=c;
            end
            k=k+1;
        end
    end
end

It should also be noted that I have used this bisect method before and it does work so I don't think the problem is with that function.

4
  • Try adding a line that just has the character i below the t(i) = bisect(f, ...) and run the function. Then, you can watch the loop counter get printed into the MATLAB command window with each iteration. Is it doing what you expect? Is it going really slowly? Does that tell you anything? Commented Oct 8, 2013 at 18:24
  • I actually tried that by adding: fprintf('%i ' ,i); and nothing prints Commented Oct 8, 2013 at 18:46
  • It does not gets stuck in the for loop, it gets stuck in the while loop, quite sure. You can remove the for loop, it won't change the behavior. Does your function f has a root? I guess it has something to do with your function... or your initial values are not chosen properly. Commented Oct 8, 2013 at 18:57
  • Exactly - the fact that nothing printed when you inserted an fprintf call immediately after the call to bisect told us that not even a single call to bisect was completing. Therefore, the bug was in bisect, as you've since figured out. Commented Oct 8, 2013 at 23:08

2 Answers 2

2

Your error is here:

c = (a-b)/2;

You initialize a=20 and b=40. c is initially set to -10. But you really want c to be halfway between a and b, which means you want:

c = (a+b)/2;
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic, thank you. I completely overlooked that when copying my old bisect method.
0

Also, add a drawnow right after you plot statement to force MATLAB to draw graphics.

1 Comment

I added that and it still yields the same result, no graph. My guess is that it is getting stuck in the for loop, but I don't know why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.