MATLAB Answers

Displaying output for each iteration

2 views (last 30 days)
Marcus Castro
Marcus Castro on 17 Sep 2020
Edited: Stephen Cobeldick on 17 Sep 2020
I need to display the output of each iteration of this False Position method to a table. I've tried using disp() and fprintf() in various different parts of the code and can only get the last iteration. And insight helps! Thanks!
function [r, k] = NMHWP1b(f, a, b, kmax, tol)
%
% RegulaFalsi uses the regula falsi method to approximate a root of f(x) = 0
% in the interval [a,b].
%
% [r, k] = RegulaFalsi(f, a, b, kmax, tol), where
%
% f is an anonymous function representing f(x),
% a and b are the limits of interval [a,b],
% kmax is the maximum number of iterations (default 20),
% tol is the scalar tolerance for convergence (default 1e-4),
%
% r is the approximate root of f(x) = 0,
% k is the number of iterations needed for convergence.
%
if nargin < 5 || isempty(tol), tol = 1e-4; end
if nargin < 4 || isempty(kmax), kmax = 20; end
c = zeros(1,kmax);
% Pre-allocate
if f(a)*f(b) > 0
r =
'failure';
return
end
disp(
'k a b c(k) f(b)*f(c(k))')
for k = 1:kmax
fprintf(
'%2i%11.6f%11.6f%11.6f%11.6f%11.6f\n',k,a,b,c(k),f(b)*f(c(k)))
c(k) = (a*f(b)-b*f(a))/(f(b)-f(a));
% Find the x-intercept
if f(c(k)) == 0 % Stop if a root has been found
return
end
iff(b)*f(c(k)) > 0 % Check sign changes
b = c(k);
% Adjust the endpoint of interval
else
a = c(k);
end
c(k+1) = (a*f(b)-b*f(a))/(f(b)-f(a));
ifabs(c(k+1)-c(k)) < tol % Stop if tolerance is met
r = c(k+1);
return
end
end

  0 Comments

Sign in to comment.

Answers (1)

Dana
Dana on 17 Sep 2020
It's printing on every iteration, it's just printing it all on one line so it looks like only one thing is getting printed.
The reason it's getting printed all on one line even though you've used the \n newline tag in your fprintf statement is because your formatting string has spots for 6 numbers, but you're only passing 5 numbers to it. If you drop the last %11.6f (or pass another number) it should work.

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!