필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Mathematics
Mathematics 2014년 7월 19일
댓글: Mathematics 2014년 7월 19일
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
Matz Johansson Bergström 2014년 7월 19일
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에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by