I am trying to make a table with the outputs of for loop!

1 view (last 30 days)
format long
close all
clear all
clc
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 (f(xl)*f(xr)>0)
xl=xr;
else
xu=xr;
end
if abs(er)<10^-6
disp(abs(er));
break
end
end
table like;
i xl xr xu fxr er
1 0 5 10 -208.596 100
2 ** *** * *** ** **
3 ** *** ** ** ** **

Accepted Answer

Brendan Gray
Brendan Gray on 8 Nov 2017
Edited: Brendan Gray on 8 Nov 2017
If you just wish to print the output to the command window, the fprintf function is very useful for printing and formatting data.
In your code, you could do something like this:
format long
close all
clear all
clc
xu=10;
xl=0;
xrpv=0;
er=0;
f=@(x)(5*exp(0.5*x)+10-x^3.5);
fprintf('i \t\t xl \t\t xr \t\t xu \t\t fxr \t\t er\n')
for i=1:1:200;
xr=(xl+xu)/2;
fxr=f(xr);
er=((xr-xrpv)/xr)*100;
xrpv=xr;
if (f(xl)*f(xr)>0)
xl=xr;
else
xu=xr;
end
if abs(er)<10^-6
disp(abs(er));
break
end
fprintf('%i\t%8.3f\t%8.3f\t%8.3f\t%8.3f\t%8.3f\n', i, xl, xr, xu, fxr, er)
end
You can play around with spacing to get the headers to line up. In the format specifier, you use placeholders such as '%8.3f'. The percent starts the placeholder, the 8 specifies that I want the number to take up 8 spaces (this ensures the columns line up properly). The .3 indicates that I want three decimal places, and the f indicates that I want to use fixed point notation.
Here are the first few lines of output:
i xl xr xu fxr er
1 0.000 5.000 5.000 -208.596 100.000
2 2.500 2.500 5.000 2.746 -100.000
3 2.500 3.750 3.750 -59.516 33.333
4 2.500 3.125 3.125 -20.094 -20.000

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!