Making the if statement in a for loop display only one iteration of the message

34 views (last 30 days)
Hi i'm having problems getting my code to display only one line of the message in the if statement. I'm pretty sure the problem is only within my if statement. Thanks in advance for any help!
% Function nto find root of
f = @(x) x.^2 -1;
%derivatieve
d = @(x) 2*x;
N = 20;
x = 1e-7;
approxArray = [x];
residualerror = [abs(f(x))];
approximation = [x];
tol = 1e-2;
iterations = 0;
for n = 1 : N
% 1 - approx root
approxroot = ((x) - (f(x)./d(x)));
x = approxroot;
approxArray(n+1) = approxroot;
% 2 - residual error
value = (f(x));
absolutevalue = abs(value);
residualerror(n+1) = absolutevalue;
% 3 - change in approximation
xtotal = abs((approxArray(2:end) - approxArray(1:end-1)));
iterations = iterations + 1;
if abs(absolutevalue(end)) < tol && abs(xtotal(end)) < tol
disp('Convergence has been reached')
break
elseif abs(absolutevalue(end)) >= tol && abs(xtotal(end)) >= tol
disp ('Convergence has not been reached')
end
end

Answers (1)

Peter O
Peter O on 30 Aug 2020
Looks like it takes 25 iterations to converge. Are you looking for it to display at the very end a Success/Failure message? Then try this set:
if abs(absolutevalue(end)) < tol && abs(xtotal(end)) < tol
disp('Convergence has been reached')
disp ("Iterations: " + num2str(n))
break
end
if n >= N
disp ('Convergence has not been reached')
disp ("Iterations: " + num2str(n))
end
A few comments on this reformatting:
  1. Because you're using the break statement to end the FOR loop early, and this occurs only when all the convergence criteria are met, you don't need a fall-through condition (the ELSEIF) to handle the other contingency. You just need to see if you max out the iteration count and are still in the loop.
  2. Usually from a logic flow perspective, if there's an ELSEIF statement, there's also an ELSE with a third contingency. This is a style choice though, and a lot of languages don't even have ELSEIF branches.
  3. Stylistically, I could reformat the above using ELSEIF n >= N. It's my personal coding preference to write this statements separately because of my second point.
  4. I'm using the newer string style formatting to output the iteration message (note the double quotes).

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!