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

6 vues (au cours des 30 derniers jours)
Mathematics
Mathematics le 19 Juil 2014
Commenté : Mathematics le 19 Juil 2014
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 commentaire
Mathematics
Mathematics le 19 Juil 2014
Modifié(e) : Star Strider le 19 Juil 2014
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

Connectez-vous pour commenter.

Réponses (1)

Matz Johansson Bergström
Matz Johansson Bergström le 19 Juil 2014
I would use num2str(pi,5) to get a string of pi with 5 decimals, for instance.
  7 commentaires
Mathematics
Mathematics le 19 Juil 2014
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 le 19 Juil 2014
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

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by