MATLAB Answers

2 digits after the dot

7 views (last 30 days)
Shahar ben ezra
Shahar ben ezra on 11 Apr 2021
Edited: dpb on 12 Apr 2021
In the following example where do I put: ,'%0.2f'
x = [1 2 3];
vals = [2 3.3333333 6; 11 23 26];
b = bar(x,vals);
xtips1 = b(1).XEndPoints;
ytips1 = b(1).YEndPoints;
labels1 = string(b(1).YData);
xtips2 = b(2).XEndPoints;
ytips2 = b(2).YEndPoints;
labels2 = string(b(2).YData);
Same problem here:
x = 0:pi/100:2*pi;
y = sin(x);
my_num= 3.33333
text_information =['my num is : ' num2str((my_num))];
xlabel(text_information); xlabel(text_information,'interpreter','latex')
tnx :)

Accepted Answer

dpb on 11 Apr 2021
Edited: dpb on 12 Apr 2021
In the first case, you'll have to use
>> string(arrayfun(@(n)sprintf('%.2f',n),vals,'UniformOutput',false))
ans =
2×3 string array
"2.00" "3.33" "6.00"
"11.00" "23.00" "26.00"
because the string class 'fmt' optional input is only recognized for datetime or duration arguments, not numbers.
num2str() accepts a trailing format string, but has some warts that have to be aware of -- to illustrate:
>> num2str(vals(1,:),'%.2f')
ans =
>> num2str(vals(1,:).','%.2f')
ans =
3×4 char array
in the first case, if just take the wanted array row, the output of the row vector isn't three strings but only one because num2str isn't smart enough to be able to do other than just catenate the three strings in a row then return the smooshed-together char() string.
If you transpose and pass a column vector instead, then it uses strvcat() internally and you do get a char() array--but again, that's a char() array and so to use it you have to remember that each element in the array is just a single byte. It will also pad the shorter strings to the maximum length of any to retain rectangular array -- in this case that doesn't show up, in some cases the extra white space may be annoying if the usage doesn't automagically strtrim() the result.
In the second case, since you just have the single value, you can add the format string to str2num
xlabel(['my num is : ' num2str(my_num,'%0.2f')],'interpreter','latex')
NB: you don't need either the temporary variable to hold the string (although that may be convenient in more complicated cases) nor to call xlabel twice to pass the string and also set the interpreter property.
You can also avoid the catenation of the string by putting the literal text in the format string--
xlabel(num2str(my_num,'my num is: %0.2f'),'interpreter','latex')
See the doc for fprintf for all the skinny on formatting strings rules.
Shahar ben ezra
Shahar ben ezra on 12 Apr 2021
now I get it
Thank you!

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!

Translated by