MATLAB - Text Formatting
MATLAB - Modern Text Formatting
Section titled “MATLAB - Modern 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 variablesitem = "apples";count = 12;price = 0.5;
% Use compose to create a formatted stringmessage = 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"The Format Specifier
Section titled “The Format Specifier”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.
Key Fields
Section titled “Key Fields”conversion: The most important part. Specifies the notation (e.g.,dfor decimal integer,ffor fixed-point float,sfor string,efor exponential).precision: A number after a period (.). For floats, it’s the number of decimal places (e.g.,%.2ffor 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 the0flag is used).flags: Optional characters that modify the output, such as-(left-justify),+(always show sign), and0(pad with leading zeros).
Common Conversion Characters
Section titled “Common Conversion Characters”| Specifier | Description |
|---|---|
%s | Character vector or string |
%d | Signed decimal integer |
%f | Fixed-point floating-point number |
%e | Exponential notation (e.g., 3.14e+00) |
%g | More compact of %f or %e |
%% | A literal percent sign (%) |
Formatting Examples
Section titled “Formatting Examples”Example 1: Controlling Precision and Width
Section titled “Example 1: Controlling Precision and Width”val = pi;
% Default formattingcompose("Value: %f", val)ans = "Value: 3.141593"
% Two decimal placescompose("Value: %.2f", val)ans = "Value: 3.14"
% Total width of 10, padded with spacescompose("Value: |%10.2f|", val)ans = "Value: | 3.14|"
% Total width of 10, left-justifiedcompose("Value: |%-10.2f|", val)ans = "Value: |3.14 |"
% Total width of 10, padded with leading zeroscompose("Value: |%010.2f|", val)ans = "Value: |0000003.14|"Legacy Formatting Functions
Section titled “Legacy Formatting Functions”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 Windowfprintf('Processing file %d of %d...\n', 5, 100)Processing file 5 of 100...
% Print to a filefileID = 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 conversionstr1 = num2str(val)str1 = '42.127'
% With precision controlstr2 = num2str(val, 4)str2 = '42.13'