Simple problem of MATLAB related to the bisection function x
Simple problem of MATLAB related to the bisection function
xl is lower value guess and xu is upper value guess
Please help me with the code
Recall the example in class where we used the method of bisection to find a root of x*tan(x)- 3=0. In reality, this equation has an infinite number of roots. In this problem, we wish to find the first 10 positive roots of the equation. To do this, write a script that will perform the following operations: Create the vector x=0:0.1:40, evaluate f = x*tan(x)-3. Using a loop, search for sign changes between adjacent values of f, and collect these as pairs of starting points for the method of bisection. Note that only the odd-numbered pairs from (ii) bracket a root, the even-numbered pairs are around a blow up to +/-Infinity of the function - so, now construct a loop (note that using the structure startvalue:increment:endvalue is very helpful here - you can specify the increment in such a way that you skip the even-numbered pairs) that will call \"mybisecfun\" with xl and xu corresponding to odd-numbered pairs from (ii) in sequence, and thus determine the first 10 roots.Solution
Main function: Roots will be in the variable bisecroot.
clear all;
x=0:0.1:40;
for i=1:length(x)
f(i)=x(i)*tan(x(i))-3;
end
rootloc=0;
for i=1:length(f)-1
if f(i)*f(i+1)<0
rootloc= [rootloc i];
end
end
rootloc=rootloc(2:2:length(rootloc));
for i=1:10
rootpairs(i,1)=(x(rootloc(i)));
rootpairs(i,2)=x(rootloc(i)+1);
end
for i=1:10
xl=rootpairs(i,1);
xu=rootpairs(i,2);
bisecroot(i,1)=mybisecfun(xl, xu);
end
Function - \"mybisecfun\"
function [c] = mybisecfun(xl,xu)
a=xl;
b=xu;
fa=a*tan(a)-3;
fb=b*tan(b)-3;
while abs(fa*fb)>0.000001
fa=a*tan(a)-3;
fb=b*tan(b)-3;
c=(a+b)/2;
fc=c*tan(c)-3;
if fa*fc<0
b=c;
else
a=c;
end
end
end
