How to create a dynamic format specification for a string variable containing numbers
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Pierre Cilliers
il 23 Gen 2015
Modificato: Stephen23
il 23 Gen 2015
How do I create a dynamic format specification for numbers? I want to create a text string for the title or Tick Labels of a plot. The text string contains a number. The format of the number must be dynamically adapted to the magnitude of the number. I want to do something like text_str=sprintf('The number is %a.bf',n), where n is the number and the format specifiers "a" and "b" are derived from the magnitude of the number.
0 Commenti
Risposta accettata
Stephen23
il 23 Gen 2015
Modificato: Stephen23
il 23 Gen 2015
According to the sprintf documentation you can use the asterisk * character to control both the field width and precision dynamically:
Field width
Minimum number of characters to print. Can be a number, or an asterisk (*) to refer to an argument in the input list. For example, the input list ('%12d', intmax) is equivalent to ('%*d', 12, intmax).
Precision
...
Can be a number, or an asterisk () to refer to an argument in the input list. For example, the input list ('%6.4f', pi) is equivalent to |('%.*f', 6, 4, pi)|.
If you wish to control something else about the number, such as switching between %f and %e, then you can only do this by supplying a different format string.
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!