finding root using bysection method (error)

5 views (last 30 days)
x = 0:.01:1;%used to generate the x values
y=(2.8*x.^3)-(3.5*x.^2)+(1.5*x)-(0.15+(0.1*stu_id));%Provided function
plot(x,y)
xl=0;%lower limit set as 0
xr=1;%upper limit set as 1
xc=(xl+xr)/2;
while abs(y(xc)) > 0.00001
if (y(xc) * y(xr)) < 0
xl = xc
else
xr = xc
end
xc = (xl + xr)/2;
end
fprintf('the root is %g\n' , xc)
tihis is my attempt to find the root between 0 and 1 but the answer comes to be = 2 pleese help me identyfi the error

Accepted Answer

Walter Roberson
Walter Roberson on 23 Feb 2011
Define your y as:
y = @(x) (2.8*x.^3)-(3.5*x.^2)+(1.5*x)-(0.15+(0.1*stu_id));
and make your plot
plot(x, y(x));
I'm surprised that the program didn't bomb out on you complaining that indices must be logical or positive integers.
  2 Comments
buxZED
buxZED on 23 Feb 2011
thanks for the answer
can you claryfy the the difference and why we write the function in such format
y=f(x)
y=@x f(x)
Walter Roberson
Walter Roberson on 23 Feb 2011
y = f(x) evaluates f(x) with the current values of x and creates a matrix (or vector) of results, which it stores in y. That matrix (or vector) of results is indexed by integer indices -- y(1) for the first, y(2) for the second, and so on.
y = @(x) f(x)
makes y an anonymous function. You can pass y an array (or vector) of values, and the function f will be evaluated on those values.
For example, with the code you had,
y(pi) would have tried to index the already-calculated vector to find the pi'th element, which would be an error. But with the alternate version, pi would be substituted at run time as x in the expression for f(x), and that particular value would be returned.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!