0
disp('iteration   xl       xu       xr       £a(%)');   
xu=10;
xl=0;
xrpv=0;er=0;
f=@(x)(5*exp(0.5*x)+10-x^3.5);
for i=1:1:200;
xr=(xl+xu)/2;
fxr=f(xr);
er=((xr-xrpv)/xr)*100;
xrpv=xr;
if abs(er)<10^-6
    disp(abs(er));
    break
end
if (f(xl)*f(xr)>0)
    xl=xr;
else
    xu=xr;
end
fprintf('&d %f %f %f %f',i,xl,xu,xr,er)
end

i am trying the make table from outputs in for loop like;

  • xl xr xu ea%
  • 0 5 10 100
  • 1 * * *
  • 2 * * *

1 Answers1

0

An easy way to plot aligned text in the command window is to use tabs. I recommend using fprintf for the header too. I changed the first and 20th line:

fprintf('it. \t xl  \t   xu  \t  xr \t   ea%%\n');   
xu=10;
xl=0;
xrpv=0;er=0;
f=@(x)(5*exp(0.5*x)+10-x^3.5);
for i=1:1:200
    xr=(xl+xu)/2;
    fxr=f(xr);
    er=((xr-xrpv)/xr)*100;
    xrpv=xr;
    if abs(er)<10^-6
        disp(abs(er));
        break
    end
    if (f(xl)*f(xr)>0)
        xl=xr;
    else
        xu=xr;
    end
    fprintf('%3d \t%.1f \t%.1f \t%.1f \t%.1f\n',i,xl,xu,xr,er)
end

And the result is this:

it.      xl        xu     xr       ea%
  1     0.0     5.0     5.0     100.0
  2     2.5     5.0     2.5     -100.0
  3     2.5     3.8     3.8     33.3
  4     2.5     3.1     3.1     -20.0
  5     2.5     2.8     2.8     -11.1
...

A similar result could be obtained by saving i,xl,xu,xr,er on each line of a matrix that could be displayed as a table. You could also use a table variable as a storage variable that could be displayed as you asked but this depends on how you are using the data in the following code.

m3tho
  • 602
  • 6
  • 11
  • 1
    [Relevant reading on the difference between `fprintf` and `disp(sprintf())`](https://stackoverflow.com/a/33520146/5211833) (Answer's mine) – Adriaan Nov 08 '17 at 10:21