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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by