MATLAB Answers

Not able to stop value of iterations

1 view (last 30 days)
Nilaa Maragathavelan
Nilaa Maragathavelan on 27 Nov 2020
Edited: VBBV on 27 Nov 2020
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

  0 Comments

Sign in to comment.

Answers (2)

VBBV
VBBV on 27 Nov 2020
Edited: VBBV on 27 Nov 2020
%if true
function
...
end
Add a missing end to close function

  3 Comments

Nilaa Maragathavelan
Nilaa Maragathavelan on 27 Nov 2020
yeah tried that...still not helping. the code iterates for the given number of iterations without stopping
VBBV
VBBV on 27 Nov 2020
%if true
function [x]=newton(R,f,Re,x0,maxiter,tol)
Try without the iteration index i as the function output
VBBV
VBBV on 27 Nov 2020
Try to check if the two functions that are being called
(colebrook(R,f,Re)/colebrook_deriv(R,f,Re))
Have any indefinite criteria inside them. The other way is to increase the tolerance so that it enters if condition

Sign in to comment.


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?

  0 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by