MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Formatting Text


To convert data to text and control its format, you can use formatting operators with
common conversion functions, such as num2str and sprintf. These operators control
notation, alignment, significant digits, and so on. They are similar to those used by the
printf function in the C programming language. Typical uses for formatted text include
text for display and output files.

For example, %f converts floating-point values to text using fixed-point notation. Adjust
the format by adding information to the operator, such as %.2f to represent two digits
after the decimal mark, or %12f to represent 12 characters in the output, padding with
spaces as needed.

A = pi*ones(1,3);
txt = sprintf('%f | %.2f | %12f', A)

txt =
'3.141593 | 3.14 | 3.141593'

You can combine operators with ordinary text and special characters in a format specifier.
For instance, \n inserts a newline character.

txt = sprintf('Displaying pi: \n %f \n %.2f \n %12f', A)

txt =
'Displaying pi:
3.141593
3.14
3.141593'

Functions that support formatting operators are compose, num2str, sprintf, fprintf,
and the error handling functions assert, error, warning, and MException.

Fields of the Formatting Operator


A formatting operator can have six fields, as shown in the figure. From right to left, the
fields are the conversion character, subtype, precision, field width, flags, and numeric
identifier. (Space characters are not allowed in the operator. They are shown here only to
improve readability of the figure.) The conversion character is the only required field,
along with the leading % character.

6 Characters and Strings

Free download pdf