How to create a dynamic format specification for a string variable containing numbers

9 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Stephen23
Stephen23 am 23 Jan. 2015
Bearbeitet: Stephen23 am 23 Jan. 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.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by