function handles and anonymous functions

hello everyone,
I have a problem doing the following question.
Write a function xb=bisection(f, a, b, tol) and a function xn=newton(f,x0,tol) which both ?nd a zero of f(x) in the interval [a,b], using the bisection and newton algorithms. For the newton function, use the function deriv from problem (2) of this assignment to compute the derivative of the function at each iteration. Then, ?nd the zero of the following functions near the given points: f(x) = cos(x 2) + sin(2x) near x = 2 g(x) = x-5ln(x) near x = 1 Also, display the number of iterations each method takes to ?nd the zero. In writing the driver routine that calls bisection and newton. This is what i did, but its not returning anything. The code is not doing anything, plus its not printing the iteration number of each method
This is the bisection part
function x = bisection(f,a,b,tol)
x =( b-a)/2;
left = a;
right=b;
i =0;
while abs(f(x))>tol
sign = f(x)/abs(x);
signleft= f(left)/abs(f(left));
if signleft <0 && sign >0
right= x;
else
left =x;
end
x =(right-left)/2;
i = i+1;
end
fprintf('bisection Iteration =%i\n',i)
This is newton part
function xn = newton(f,x0,tol)
xn = x0;
i= 0;
while abs(f(xn)) > tol
xn = xn - f(xn)/deriv(f,xn,tol);
i=i+1;
end
fprintf('newton Iteration =%i\n',i)
This is test root part
f = @(x)(cos(x/2)+sin(2*x));
g = @(x)(x-5*ln(x));
tol = 10 *exp(-6);
y= bisection(f,1,4,tol);
x= bisection (g,0,1.5,tol);
h = newton(f,2,tol);
k= newton(g,1,tol);
fprintf('%f %f\n',y,x)
fprintf('%f %f\n',h,k)
**
This is the deriv function
function D= deriv(f,a,h)
D = (f(a+h) -f(a-h))/2*h;
end
**

댓글 수: 1

Stephan
Stephan 2018년 7월 31일
편집: Stephan 2018년 7월 31일
Hi, copy the code in here, mark it and use the {}Code Button. This will increase your chance getting an answer.
Best regards
Stephan

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

질문:

2018년 7월 31일

편집:

2018년 7월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by