Filter löschen
Filter löschen

finding root using bysection method (error)

2 Ansichten (letzte 30 Tage)
buxZED
buxZED am 23 Feb. 2011
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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 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 Kommentare
buxZED
buxZED am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by