7.4) Forming Strings From Data: sprintf
The Matlab function "sprintf" formats numerical data into strings. It is a very useful tool if you want to incorporate numerical data into strings.
The syntax is as follows:
[matlab]
str=sprintf(format,A)
[/matlab]
where format is a string that describes the formatting and "A" is an array (scalar). The format argument controls the output format in terms of field width, precision and numerical notation
- The fixed width is the total width (in characters) of the string
- precision is the number of numbers to the right of the decimal place
- the conversion character specifies the numerical format, e.g., e=exponential, g=compact and f=fixed point notation
Examples of sprintf in use are:
Command | Result |
sprintf('%e', pi) | 3.14159eE+00 |
sprintf('%g', pi) | 3.14159 |
sprintf('%12.9e', pi) | 3.141592654E+00 |
sprintf('%13.15f', pi) | 3.141592653589793 |