how to tabulate this results using fprintf?

clc
clear all
close all
f=@(x) ((x^3)-x-3)
Ea=100
i=0
xl=0
xu=3
fl=f(xl);
fu=f(xu);
display('i xl xu f(xl) f(xu) xr f(xr) Ea')
while Ea > 10^-3
xr=(xl+xu)/2
fr=f(xr)
if fl*fr>0
Ea=abs((xl-xr)/xl*100);
xl=xr
fprintf('%2.0f %12.5f %12.5f %12.5f %12.5f\n' ...
, i + 1, xl, xu, fl, fu, xr, fr, Ea);
else
Ea=abs((xu-xr)/xu*100);
xu=xr
end
i=i+1
fxr(i) = fr;
Eav(i) = Ea;
iv(i) = i;
end
figure
plot(iv,Eav,'-o')
xlabel('i');
ylabel('|Ea|');
title('|Ea| versus i');
figure
plot(iv,fxr,'-o')
xlabel('i');
ylabel('fxr');
title('fxr versus i');

 Accepted Answer

You only have 5 format fields in your fprintf call.
Try this (with all 8):
fprintf('%2.0f %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f\n', i + 1, xl, xu, fl, fu, xr, fr, Ea);
Experiment to get the result you want.

2 Comments

I tried but there is no tabulated solution. I want all type of variables like Ea values in a column.
It worked when I ran it, and printed this to the Command Window:
i xl xu f(xl) f(xu) xr f(xr) Ea
1 1.50000 3.00000 -3.00000 21.00000 1.50000 -1.12500 Inf
5 1.59375 1.68750 -3.00000 21.00000 1.59375 -0.54556 6.25000
6 1.64063 1.68750 -3.00000 21.00000 1.64063 -0.22464 2.94118
7 1.66406 1.68750 -3.00000 21.00000 1.66406 -0.05610 1.42857
9 1.66992 1.67578 -3.00000 21.00000 1.66992 -0.01311 0.35211
11 1.67139 1.67285 -3.00000 21.00000 1.67139 -0.00231 0.08772
14 1.67157 1.67175 -3.00000 21.00000 1.67157 -0.00096 0.01096
15 1.67166 1.67175 -3.00000 21.00000 1.67166 -0.00028 0.00548
17 1.67168 1.67171 -3.00000 21.00000 1.67168 -0.00012 0.00137
18 1.67170 1.67171 -3.00000 21.00000 1.67170 -0.00003 0.00068
I needed to add semicolons to several statements that needed them (to prevent them being printed to the Command Window). After that, I got the result I posted here.

Sign in to comment.

More Answers (0)

Categories

Find more on Scripts 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!