Matlab - short format of number variable in the plot title

萝らか妹 提交于 2019-12-24 01:56:10

问题


I am trying to place a variable into a plot title but I cannot produce formatting of 4 decimal places. How to avoid the float format in the title?

This is the code I use

subplot(3,2,1);
hist(X,10);
str=sprintf('X N=%d,Y=%d',N,Y)
M=sum(X)/N
Mean=sprintf('Mean=%0.4d',M)
title({str,Mean})

回答1:


You need to use %f as the format specifier for float values. Changing your code

Mean=sprintf('Mean=%0.4d',M)

to

Mean=sprintf('Mean=%0.4f',M)

will print M with 4 decimal places of accuracy. If you want to print M without any decimal places then you need to use %.0f

Mean=sprintf('Mean=%.0f',M)

%.0f will print a double or float value with 0 decimal places and appear as if you printed an integer with %d.


If your variable X has N elements than using the builtin MATLAB function mean() will produce the same output as sum(X) / N.


Note: You should be careful of your variable names. MATLAB includes a mean() function which you don't want to overwrite by calling a variable mean. MATLAB variable names are case-sensitive so Mean is ok but mean isn't.




回答2:


You can use num2str function. For example:

mean(y)
a=num2str(ans,5)
plot(x,y)
title(['sometext ' a])

5 in num2str parameters shows maximum number of significant digits. And a is now a string. By the way you can use mean build-in function instead your formula.



来源:https://stackoverflow.com/questions/33114938/matlab-short-format-of-number-variable-in-the-plot-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!