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

1 回表示 (過去 30 日間)
Muhammed Tugrul
Muhammed Tugrul 2017 年 11 月 7 日
回答済み: Brendan Gray 2017 年 11 月 8 日
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 ** *** ** ** ** **

採用された回答

Brendan Gray
Brendan Gray 2017 年 11 月 8 日
編集済み: Brendan Gray 2017 年 11 月 8 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by