finding root using bysection method (error)
1 次查看(过去 30 天)
显示 更早的评论
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
采纳的回答
Walter Roberson
2011-2-23
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 个评论
Walter Roberson
2011-2-23
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.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!