Clear Filters
Clear Filters

Displaying output for each iteration

10 views (last 30 days)
Marcus Castro
Marcus Castro on 17 Sep 2020
Edited: Stephen23 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 =
'k a b c(k) f(b)*f(c(k))')
for k = 1:kmax
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
iff(b)*f(c(k)) > 0 % Check sign changes
b = c(k);
% Adjust the endpoint of interval
a = c(k);
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);

Answers (1)

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.


Find more on Creating and Concatenating Matrices 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!