Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, i have a MATLAB question, and there are a lot of the same answers on chegg f

ID: 3210304 • Letter: H

Question

Hi, i have a MATLAB question, and there are a lot of the same answers on chegg for this question, but they run errors when tried.

please test the function before you post the CORRECT answer.

thank you!

bisection method

create a function with the headerline root = findroots(x, y, tol) that will output all of the roots of a function (along the interval of x) using the bisection method.

This function uses the inputs

x which is a vector that has the starting and ending point over which you are looking for roots (x = starting:interval:ending)

y which is an inline function (see examples below)

tol which is the tolerance used to find the roots (see examples below)

Note: y is a function NOT an array

Output the roots in the array root.

Rules: you cannot use the functions roots, fzero or feval

Test your function

>> y = inline('cos(x)-x', 'x');

>> R = findroots(0:0.1:2, y, 0.0001)

R =

   0.7391


>> y = inline('cos(x)', 'x');

>> R = findroots(0:0.1:10, y, 0.0001)

R =

   1.5707    4.7123 7.8539


>> y = inline('sin(x)', 'x');

>> R = findroots(0:0.1:20, y, 0.0001)

R =

   3.1416    6.2832 9.4248   12.5664 15.7080 18.8496

Explanation / Answer

%%% Matlab function

function root = findroots(x,y,tol)
y1=diff(y(x)> 0);
k=1;
root=[];
for n=1:length(y1)
if abs(y1(n)~=0);
lo(k)=n;
k=k+1;
end
end
%%% lo contains the location of interval in which roots lies
for k=1:length(lo)
  

if (y(x(lo(k)))>0)
a=x(lo(k));
b=x(lo(k)+1);
else
b=x(lo(k)+1);
a=x(lo(k));
end




for n=1:100
l1=y(a);
l2=y(b);
  
c(n)=(a+b)/2;
  
l3=y(c(n));
if (n>2)
if (abs( c(n)-c(n-1))< tol)
break;
end
end
  
if ( l3 > 0 )
a=c(n);
else
b=c(n);
end

end
root(k)=c(n);
end


if (length(lo)==1)
if y(x(lo)) >0
a=x(lo-1);
b=x(lo+1);
else
a=x(lo+1);
b=x(lo-1);
end
for n=1:100
l1=y(a);
l2=y(b);
  
c(n)=(a+b)/2;
  
l3=y(c(n));
if (n>2)
if (abs( c(n)-c(n-1))< tol)
break;
end
end
  
if ( l3 > 0 )
a=c(n);
else
b=c(n);
end
end
root=c(n);
end


end

OUTPUT

>> y=inline('cos(x)-x','x');
>> findroots(0:0.1:2,y,0.0001)

ans =

0.739160156250000

>> y=inline('cos(x)','x');
>> root=findroots(0:0.1:10,y,0.0001)

root =

1.570800781250000 4.799902343750000 7.854003906250000

>> y=inline('sin(x)','x');
>> root=findroots(0:0.1:20,y,0.0001)

root =

Columns 1 through 6

0.099902343750000 3.141503906250000 6.200097656250000 9.424707031250001 12.500097656250000 15.707910156250000

Column 7

18.899902343750000

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote