How to automatically change the number of digits to the right of the decimal point in the fprintf function

12 ビュー (過去 30 日間)
Hi all,
I need your help. For the ‘fprintf’ function. The corresponding part of the number of digits to the right of the decimal point (eg. %f). Can it be modified (it is changing) in a program, in accordance with certain characteristics of the information where it is needed that it fits to a specific fractional value and that obviously it would not be the same in all the cases?. Says, if in a data tenths are needed (%8.1f), for other data to ten-thousandth (%8.4f), etc. and that it fits automatically, in accordance with a criterion of operation that says the significant numbers needed.
Any hint are welcome. Thx
Antonio

採用された回答

Sean de Wolski
Sean de Wolski 2014 年 9 月 25 日
You can use * as a wildcard to point at inputs:
sprintf('%*.*f', 6, 4, pi)
And in the doc for sprintf under "field width"

その他の回答 (2 件)

Joseph Cheng
Joseph Cheng 2014 年 9 月 25 日
編集済み: Joseph Cheng 2014 年 9 月 25 日
If i understand your question correctly make the '%f' statement a string variable outside of the fprintf() command that us used in the fprintf or designate a significant digit variable that is referenced like below when fprintf is called.
example:
%perform some math operation
sigfig = 4;
%%some stuff going on here.
%later on print some value maybe performed in a function?
fprintf(fid,['%8.' num2str(sigfig) 'f\n\r'],X);
which then when you perform the operation you would update the specific number of significant digits in the sigfig variable which then is referenced in your fprintf statment.

Antonio Trujillo-Ortiz
Antonio Trujillo-Ortiz 2014 年 9 月 25 日
Thanks to Sean and Joseph. Sean answer Works fine. I did this:
Eg.
d = 3; sprintf('%*.*f', 6, d, pi)
Antonio

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by