I have a problem with fprintf function, MATLAB

1 次查看(过去 30 天)
Hello,
I have a question about my matlab code. I wrote my code, but when I run my code, output look is wrong.
I want a output that gives me my results in tabulated form in which the first column shows the number of terms ( in my code m represents the term) , the second column lists the approximation value ( in my code sum represent the app. value), third column shows the true value( in my code truevalue represents that), fourth column show the Et true percent relative error (in my code Et represent that) and finally fifth column represents the Ea error (in my code Ea represents that).
But when I run my code, the output is very wrong.
Thanks for the help.
clc
clear all
close all
x = -2.5;
truevalue = log(exp(1)+x); %my true value is -1.5220
Ea= 100;
Es = 0; %First error
m=1;
sum=1;%sum is represents the formula of ln(e+x) given in the question.
fprintf('\tn\t app.\t true value\t Et\t Ea\n')
while abs(Ea) >= Es
Es = (0.5*10^-2)/100;
sump = sum;
sum = sum + (((-1)^(m-1))/m)*((x/m)^m); %sum is my approximate value
Et = abs(( ( truevalue - sum ) / truevalue )*100);
Ea = (( sum - sump ) / sum ) * 100;
fprintf('%10.4f\t\t %10.4f\t %10.4f\t\t %10.4f\n',m,sum,truevalue,Et,abs(Ea))
m = m+1;
end

采纳的回答

Stephen23
Stephen23 2019-3-27
编辑:Stephen23 2019-3-27
You only defined four number conversions within the format string, but you have provided five inputs to fprintf. Start by writing the format string with the correct number of conversions.
To align the columns simply specify the fieldwidths (and avoid unpredictable tabs):
% Print header:
fprintf('%10s %10s %10s %10s %10s\n','m','app','truevalue','Et','Ea');
for...
....
% Print data:
fprintf('%10.4f %10.4f %10.4f %10.4f %10.4f\n',m,sum,truevalue,Et,abs(Ea))
end
Which prints this:
m app truevalue Et Ea
1.0000 -1.5000 -1.5220 1.4434 166.6667
2.0000 -2.2812 -1.5220 49.8881 34.2466
3.0000 -2.4742 -1.5220 62.5626 7.7967
4.0000 -2.5123 -1.5220 65.0690 1.5184
5.0000 -2.5185 -1.5220 65.4797 0.2482
6.0000 -2.5194 -1.5220 65.5370 0.0346
7.0000 -2.5195 -1.5220 65.5439 0.0042
8.0000 -2.5195 -1.5220 65.5447 0.0005
9.0000 -2.5195 -1.5220 65.5448 0.0000
  1 个评论
hgrlk
hgrlk 2019-3-27
Oh true!!
Thanks a lot for the answer, I changed my code and now it worked perfectly!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Text Data Preparation 的更多信息

标签

产品


版本

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by