HOWTO · MATLAB

MATLAB Fprintf Table

Learn how to use MATLAB's fprintf function to print formatted text and create tables. This guide covers essential techniques for displaying data clearly, including formatting numbers, aligning text, and writing output to files. Perfect for beginners and experienced users alike, discover the power of fprintf to enhance your MATLAB programming skills.

On this page

Use MATLAB fprintf with a format specification and matching values to print a readable table. Put literal spaces between fields when using field-width conversions, and end each row with a newline escape (\n). Tabs (\t) are another separator option, but tab stops may not align columns consistently. The same call can write to the command window or to a file.

Understand fprintf Format Specifications

The basic form is fprintf(formatSpec, values...). The format specification is a character vector or string containing ordinary text and conversion specifications. Each conversion consumes a supplied value: %s formats text, %d formats an integer, and %f formats a fixed-point number. For example, fprintf('Count: %d\n', 3) writes a label, the value, and a newline.

A conversion can include flags, a minimum field width, and precision, as in %-10s or %8.2f. The minus flag left-aligns a value; without it, a value is right-aligned. Precision in %8.2f requests two digits after the decimal point. Width is a minimum, so a longer value extends beyond it rather than being cut off. A percent sign in the output is written as %%.

When values include a matrix, fprintf processes its elements in MATLAB column-major order and repeats the format as needed. It does not infer that each format conversion represents one matrix column. For row-oriented tables, explicitly index the row values, as in the example below. See the MathWorks fprintf reference for the full syntax and conversion options.

Build a Table from MATLAB Data

Keep headers and data in a consistent order. This example separates fields with literal spaces and ends each row with \n; the width conversions reserve space so the values line up. A \t escape can separate fields too, but tab stops do not guarantee consistent alignment when text lengths or display settings vary. The loop supplies one row of values at a time. It uses ordinary MATLAB syntax that is also accepted by the configured Octave runtime.

Run this example:

names = {'Ava', 'Milo', 'Zoe'};
scores = [85, 92, 78];
means = [91.25, 84.50, 96.75];

fprintf('%-8s %6s %8s\n', 'Name', 'Score', 'Mean');
for k = 1:numel(names)
    fprintf('%-8s %6d %8.2f\n', names{k}, scores(k), means(k));
end
Name      Score     Mean
Ava          85    91.25
Milo         92    84.50
Zoe          78    96.75

The header and row formats each contain three conversions in the same order as the supplied values: name, score, then mean. The newline ends each printed row. If instead you pass a matrix directly, remember that MATLAB visits its first column from top to bottom before moving to the next column; arrange data or use indexing to match the order your table needs.

Align Columns and Format Numbers

Choose widths based on the longest expected heading or value. In the example, %-8s reserves at least eight characters for each name and aligns it to the left. %6d reserves six characters for the integer score, while %8.2f reserves eight characters and displays two decimal places for the mean. A field expands when its contents exceed the requested width, so inspect representative values when designing a fixed-width report.

Tabs (\t) move to the next tab stop, not to a fixed character position after every value. They can look misaligned when text lengths vary or when output is viewed with different tab settings. For predictable columns, use width conversions such as %-12s %8.2f and choose a text editor or console with a monospaced font. Precision changes displayed rounding; it does not change the stored value.

Write Formatted Table Output to a File

Pass a file identifier as the first argument to fprintf to send the same formatted text to a file. Open the file with fopen, check that it opened, and close it when writing is complete. This self-contained example writes a small table to a temporary path and uses onCleanup so the identifier is closed even if later code exits early.

names = {'Ava', 'Milo'};
scores = [85, 92];
path = [tempname(), '.txt'];
fileID = fopen(path, 'w');
if fileID >= 0
    closeFile = onCleanup(@() fclose(fileID));
    fprintf(fileID, '%-8s %6s\n', 'Name', 'Score');
    for k = 1:numel(names)
        fprintf(fileID, '%-8s %6d\n', names{k}, scores(k));
    end
    clear closeFile
end

The 'w' mode creates or replaces the target file, so choose a path that is safe to overwrite. If fopen returns a negative identifier, the file could not be opened; check the path and permissions before writing. For repeated reports, construct the output path deliberately and close each identifier after its writes to release the file.

Troubleshoot Common Table-Formatting Issues

If columns show the wrong values, compare the conversion order with the order of the values passed to fprintf. Each %s, %d, or %f must receive a compatible value; a mismatch can produce misleading output or a formatting warning. For matrices, column-major traversal often explains why values appear in an unexpected sequence. Use scalar row indexing or transpose/rearrange data deliberately, rather than assuming fprintf maps conversions to columns.

If columns do not line up, use explicit widths instead of tabs, and allow for the longest possible text and number. If decimals appear rounded, adjust the precision in a conversion such as %.4f; this affects only the text representation. If a file is blank or incomplete, verify that fopen succeeded, direct each write to its file identifier, and close the file after the final row. Keep the format conversions, supplied values, and separators in the same order to make the table easy to check and maintain.