Open to feedback of working code (please review)

2 views (last 30 days)
Hey whats up folks, I was you could give my code a look .I have implements both the backward Euler method and Newtons method with f=f(t,y), dfdy=f'(t,y), maxiter=maximum number of iterations, and N=the number of steps. My code is below. I am open to feedback and possible changes. Any help would surely be appreciated.
my code:
function [t,w] = backeuler_four(f, dfdy, a, b, alpha, N, maxiter, tol)
h = (b-a)/N;
t = a:h:b;
w = t*0;
w(1) = alpha;
for i = 1:N
w0=w(i);
wj=w0;
for j=1:maxiter
wj=wj-(wj - w0 - h*f(t(i+1),wj)) / (1 - h*dfdy(t(i+1),wj));
error=(wj - w0 - h*f(t(i+1),wj)) / (1 - h*dfdy(t(i+1),wj));
fprintf('%d %g\n', j, abs(error));
if abs(error)<=tol, break;end
end
end
fprintf('\n');
if abs(error) > tol, error('No Newton convergence.'); end
w(i+1)=wj;

Accepted Answer

Walter Roberson
Walter Roberson on 2 Dec 2021
if abs(error)<=tol, break;end
That only breaks out of one level of for loop.
Suppose you get convergence at i = 2, j = 7. Then you leave the for j loop. But you are still inside the for i loop, and you overwrite error and so on. So your final test is really testing whether you got convergence when i == N.
  3 Comments
Walter Roberson
Walter Roberson on 2 Dec 2021
Edited: Walter Roberson on 2 Dec 2021
If you need a solution for each i value, then do not break out of the inner loop -- but in such a case, you should possibly store the error for each i value.
If you only need to execute until you find one solution, then you should break out of the outer loop.
function [t,w] = backeuler_four(f, dfdy, a, b, alpha, N, maxiter, tol)
h = (b-a)/N;
t = a:h:b;
w = t*0;
w(1) = alpha;
converged = false;
for i = 1:N
w0=w(i);
wj=w0;
for j=1:maxiter
wj=wj-(wj - w0 - h*f(t(i+1),wj)) / (1 - h*dfdy(t(i+1),wj));
error=(wj - w0 - h*f(t(i+1),wj)) / (1 - h*dfdy(t(i+1),wj));
fprintf('%d %g\n', j, abs(error));
if abs(error)<=tol
converged = true;
break;
end
end
if converged; break; end
end
fprintf('\n');
if ~converged
error('No Newton convergence.');
end
w(i+1)=wj; %not sure what this is about

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!