Info

This question is closed. Reopen it to edit or answer.

Not able to stop value of iterations

2 views (last 30 days)
Nilaa Maragathavelan
Nilaa Maragathavelan on 27 Nov 2020
Closed: MATLAB Answer Bot on 20 Aug 2021
This is my code. I get my x value correctly, and stops there. The if condition is not iterating and I'm not able to find the root or the number of iterations.
Can anybody please clear me about this?
function [x,i]=newton(R,f,Re,x0,maxiter,tol)
for i=1:maxiter
x=x0-(colebrook(R,f,Re)/colebrook_deriv(R,f,Re))
if (x-x0)<tol
break
disp(['root= ',num2str(x)])
end
fprintf('The number of iterations is: %d\n',i)
end

Answers (1)

Alan Stevens
Alan Stevens on 27 Nov 2020
Edited: Alan Stevens on 27 Nov 2020
Better as something like
tol = 10^-8; % or whatever you desire
maxiter = 100; % ditto
err = 1;
its = 0;
while err>tol && its<maxiter
x=x0-(colebrook(R,f,Re)/colebrook_deriv(R,f,Re));
err = abs(x-x0);
x0 = x;
its = its+1;
end
disp(['root= ',num2str(x)])
fprintf('The number of iterations is: %d\n',its)
and, come to think of it, shouldn't colebrook and colebrook_deriv be functions of x, or, alternatively, shouldn't x and x0 be f and f0?

Tags

Community Treasure Hunt

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

Start Hunting!