First value of an array does not display with a decimal
Show older comments
I am trying to print an array which display the values of x y and z on every change of x and z, but the first value os always formated a different way if z is an integer. Here is the awnser I get:

And here is my code:
zp=input('Įveskite pradinę z vertę: ');
zg=input('Įveskite galutinę z vertę: ');
hz=input('Įveskite z vertės pokytį: ');
xp=4;
hx=0.3;
x=xp;
disp(' x y z');
for z=zp:hz:zg
if z>=x
y=sin(x).*cos(x);
else
y=log10(xp).*log(z);
end
disp([x y z]);
x=x+hx;
end
Accepted Answer
More Answers (2)
Torsten
on 22 Nov 2025
If you like it more, you can use
sprintf('%f %f %f',[x, y, z])
instead of
disp([x y z]);
1 Comment
The default format for MATLAB display in the command window is '%g" (OK, so it is complicated thing that renders basically as, not precisely) which has the characteristic that integer-valued doubles are printed as integers, not floating point. This has a little advantage in normal use in that one can tell if a value is exactly an integer or has some rounding error that is not shown if the displayed result is "0.0" instead of just "0".
But, to control the actual precision, one must set the format explicitly or use a different format in the command window; there are only a relatively few of those available, however, and a specific number of digits in '%f" format isn't one of them(*).
zp=input('Įveskite pradinę z vertę: ');
zg=input('Įveskite galutinę z vertę: ');
hz=input('Įveskite z vertės pokytį: ');
xp=4;
hx=0.3;
x=xp;
disp(' x y z');
fmt=[repmat('%8.4f',1,3) newline]; % build the formatting string
for z=zp:hz:zg
if z>=x
y=sin(x).*cos(x);
else
y=log10(xp).*log(z);
end
fprintf(fmt,x,y,z); % print using the format
x=x+hx;
end
(*) The one exception to the general statement is format bank that sets two decimal places.
2 Comments
Default
default restores the default display format, which is short for numeric format and loose for line spacing. (since R2021a)
So the default is not %g .
format short examines the set of values to be displayed, and if they are all integer-valued and have absolute value at most 999999999, then it displays them in integer format. If even one of them is non-integer then a format with decimal points is used.
format short
9e8
-9e8
9e8+0.5
[9e8 9e8]
[9e8 9e8]+[0 0.5]
- all integers in range: displays as integers
- single non-integral number: displays as single number including exponent
- multiple numbers with at least one non-integral: displays leading scale factor, then below that displays scaled numbers with no exponent and 4 decimal places
Walter Roberson
on 23 Nov 2025
I see your edits, but it is still true that the default display format is not %g but rather "format short"
Categories
Find more on Multirate Signal Processing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!