Is there any way to control the number of decimal places for the outputs?

2 次查看(过去 30 天)
I am studying root finding problem in numerical analysis. I have written down MATLAB codes for Bisection and Newton methods. They are running fine but I need to have different number of decimal places in the output for different questions. But Matlab either give 4 or 15 decimal places with default and format long settings.
Is there any way to control the number of decimal places in the output through code or by any other mean?
  1 个评论
Mathematics
Mathematics 2014-7-19
编辑:Star Strider 2014-7-19
For instance, I want to have first column as integers (iteration count) and in the remaining columns I want to have 7 decimal places in the output of the following code (out= [iter, a, b, m, ym, bound]; disp(out)). How can i achieve this? Any suggestion?
f=inline('x.^3-3*x.^2+1'); %
a=0; b=1; kmax=26; tol=0.00001;
ya=f(a); yb=f(b);
if sign(ya)== sign(yb), error('function has same sign at end points'), end
disp('step a b m ym bound')
for k=1:kmax
m=(a+b)/2; ym=f(m); iter=k; bound=(b-a)/2;
out= [iter, a, b, m, ym, bound]; disp(out)
if abs(ym)<tol, disp('bisection has converged'); break; end
if sign(ym) ~= sign(ya)
b=m; yb=ym;
else
a=m; ya=ym;
end
if (iter >= kmax), disp('zero not found to desired tolerance'), end
end
Shah

请先登录,再进行评论。

回答(1 个)

Matz Johansson Bergström
I would use num2str(pi,5) to get a string of pi with 5 decimals, for instance.
  7 个评论
Mathematics
Mathematics 2014-7-19
This works fine but shows only the last iteration results. I need to see/print the iterations as they progress i.e. I want to see all iterations on my screen. Would you suggest a fix for this?
Shah
Mathematics
Mathematics 2014-7-19
It is fixed. I added out= [iter, a, b, m, ym, bound]; fprintf(1, '%.0f %.5f %.5f %.5f %.6f %.6f\n',out') inside the loop and got the desired output form.
Thanks indeed for your valuable suggestions!
Shah

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by