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

14 ビュー (過去 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 Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by