Skip to content

MATLAB - Text Formatting

Effective text formatting is crucial for displaying results, creating reports, and building user interfaces. Modern MATLAB offers powerful and flexible tools for this, primarily through string arrays and the compose function, while also supporting traditional C-style functions like sprintf and fprintf.

Modern Approach: String Arrays and compose

Section titled “Modern Approach: String Arrays and compose”

Since R2016b, MATLAB introduced the string data type (using double quotes ""), which offers significant advantages over traditional character vectors (using single quotes ''). For formatting, the compose function is the recommended modern approach.

% Create string variables
item = "apples";
count = 12;
price = 0.5;
% Use compose to create a formatted string
message = compose("We have %d %s at $%.2f each.", count, item, price)
message =
"We have 12 apples at $0.50 each."

The power of compose becomes evident when working with arrays:

items = ["apples", "oranges"];
counts = [12, 5];
inventory = compose("- %d %s", counts, items)
inventory =
2×1 string array
"- 12 apples"
"- 5 oranges"

Both modern and legacy formatting functions use a format specifier, a string that starts with % and defines how a value should be converted to text. Its general structure is:

%[identifier][flags][width][.precision][subtype]conversion

The only mandatory parts are the % and the conversion character.

  • conversion: The most important part. Specifies the notation (e.g., d for decimal integer, f for fixed-point float, s for string, e for exponential).
  • precision: A number after a period (.). For floats, it’s the number of decimal places (e.g., %.2f for 2 places). For strings, it’s the max number of characters.
  • width: The minimum number of characters for the output. If the value is shorter, it’s padded with spaces (or zeros if the 0 flag is used).
  • flags: Optional characters that modify the output, such as - (left-justify), + (always show sign), and 0 (pad with leading zeros).
SpecifierDescription
%sCharacter vector or string
%dSigned decimal integer
%fFixed-point floating-point number
%eExponential notation (e.g., 3.14e+00)
%gMore compact of %f or %e
%%A literal percent sign (%)

Example 1: Controlling Precision and Width

Section titled “Example 1: Controlling Precision and Width”
val = pi;
% Default formatting
compose("Value: %f", val)
ans = "Value: 3.141593"
% Two decimal places
compose("Value: %.2f", val)
ans = "Value: 3.14"
% Total width of 10, padded with spaces
compose("Value: |%10.2f|", val)
ans = "Value: | 3.14|"
% Total width of 10, left-justified
compose("Value: |%-10.2f|", val)
ans = "Value: |3.14 |"
% Total width of 10, padded with leading zeros
compose("Value: |%010.2f|", val)
ans = "Value: |0000003.14|"

While compose is preferred for new code, you will frequently encounter older functions. They are still fully supported and useful.

sprintf: Format data into a character vector

Section titled “sprintf: Format data into a character vector”

sprintf works just like compose, but returns a character vector ('...') instead of a string.

name = 'Alice';
age = 30;
msg_char_vector = sprintf('User %s is %d years old.', name, age)
msg_char_vector =
'User Alice is 30 years old.'

fprintf: Format and print data to screen or file

Section titled “fprintf: Format and print data to screen or file”

fprintf applies a format and prints the result directly to the Command Window or a specified file ID. It does not return a variable containing the string.

% Print to Command Window
fprintf('Processing file %d of %d...\n', 5, 100)
Processing file 5 of 100...
% Print to a file
fileID = fopen('log.txt','w');
fprintf(fileID, 'Log entry: System is stable.\n');
fclose(fileID);

num2str: Simple Number-to-String Conversion

Section titled “num2str: Simple Number-to-String Conversion”

For basic conversion of a number to a string without complex formatting, num2str is a straightforward choice.

val = 42.126;
% Simple conversion
str1 = num2str(val)
str1 = '42.127'
% With precision control
str2 = num2str(val, 4)
str2 = '42.13'