Back to Blog

MATLAB fprintf: Formatting Output, Writing Files, and Common Mistakes

Published03/20/2026
Updated 08/20/2026
6 min read

fprintf is MATLAB's formatted-output function. Use it to print controlled text in the Command Window, send messages to standard error, or write formatted data to a text file.

The three forms to remember are:

fprintf(formatSpec, A1, ..., An)          % standard output
fprintf(fileID, formatSpec, A1, ..., An)  % file or standard error
nbytes = fprintf(...)                     % number of bytes written

If you only need a working example:

sensorID = 7;
temperature = 23.4;
fprintf('Sensor %d: %.1f C\n', sensorID, temperature)

That prints:

Sensor 7: 23.4 C

MATLAB fprintf format string and formatted output

MATLAB fprintf format specifiers

A format specifier starts with % and ends with a conversion character. Width, precision, and flags go between them.

SpecifierUseExampleOutput
%dSigned integerfprintf('%d', 42)42
%fFixed-point numberfprintf('%.2f', pi)3.14
%eScientific notationfprintf('%.2e', 0.00123)1.23e-03
%gCompact floating-point formfprintf('%.4g', pi)3.142
%sTextfprintf('%s', 'ready')ready
%cCharacterfprintf('%c', 65)A
%xHexadecimal integerfprintf('%x', 255)ff
%%Literal percent signfprintf('%.1f%%', 87.5)87.5%

In %.2f, .2 means two digits after the decimal point. In %10.3f, 10 is the minimum field width and 3 is the number of decimal places.

values = [3.14159, -12.5, 0.007];
for k = 1:numel(values)
    fprintf('%+10.3f\n', values(k));
end

Useful flags include - for left alignment, + to always show a sign, and 0 for zero padding. For example, %+08.2f formats 3.14 as +0003.14.

Newlines, tabs, and literal characters

fprintf does not add a newline. Include \n when you want the next output to start on a new line.

fprintf('Name\tValue\n')
fprintf('alpha\t%.3f\n', 1.2345)

Common special characters are:

SequenceResult
\nNew line
\tHorizontal tab
\rCarriage return
\\Literal backslash
%%Literal percent sign

This is the main difference from disp: disp adds a newline and chooses its own representation, while fprintf gives you control over the output format.

How fprintf handles vectors and matrices

MATLAB applies the format to every input element in column order. The format repeats until all values have been used.

v = [10 20 30];
fprintf('value = %d\n', v)

The single %d is reused three times, so the code prints three lines without an explicit loop.

Matrix output is where column order becomes visible:

A = [1 2 3; 4 5 6];
fprintf('%d %d\n', A)

The output is:

1 4
2 5
3 6

To print one line per row of the original matrix, transpose it before passing it to fprintf:

A = [1 2 3; 4 5 6];
fprintf('%d %d %d\n', A.')

Use .' here for a nonconjugate transpose. That distinction matters if the matrix can contain complex values.

Standard output and standard error

Without a file identifier, fprintf writes to standard output, which is file identifier 1. MATLAB reserves file identifier 2 for standard error.

fprintf('Completed %d cases\n', n)
fprintf(2, 'Warning: case %d did not converge\n', k)

Use standard error for warnings or diagnostics that a calling process should be able to separate from normal output. MATLAB's documented form is the numeric identifier 2; do not rely on fprintf('stderr', ...) as MATLAB syntax.

Write formatted text to a file

Open the file with fopen, verify that it opened, pass its identifier to fprintf, and close it when finished.

[fid, message] = fopen('temperatures.csv', 'w', 'n', 'UTF-8');
if fid == -1
    error('Could not open temperatures.csv: %s', message);
end

fprintf(fid, 'Period,Sensor1,Sensor2,Sensor3\n');

temperatures = [20.1 21.3 19.8; 22.0 23.5 21.1];
labels = {'Morning', 'Afternoon'};

for k = 1:size(temperatures, 1)
    fprintf(fid, '%s,%.1f,%.1f,%.1f\n', ...
        labels{k}, temperatures(k, :));
end

fclose(fid);

'w' creates or overwrites a file. Use 'a' when you need to append instead. MATLAB currently defaults to UTF-8 when a file is opened for writing without an encoding, but specifying 'UTF-8' makes the file contract explicit.

Close files even when code fails

In a function, an onCleanup object can close the file if the function finishes normally, throws an error, or is interrupted with Ctrl+C.

function writeReport(filename, values)
    [fid, message] = fopen(filename, 'w', 'n', 'UTF-8');
    if fid == -1
        error('Could not open %s: %s', filename, message);
    end

    cleanup = onCleanup(@() fclose(fid));
    fprintf(fid, 'Index,Value\n');
    fprintf(fid, '%d,%.6g\n', [(1:numel(values)); values(:).']);
end

Keep the cleanup object in the function workspace. When MATLAB destroys it, the registered fclose call runs.

The return value counts bytes

Capture the return value when you need to confirm how much output was written:

nbytes = fprintf(fid, 'Result: %.3f\n', result);

For a file, nbytes depends on the file's character encoding. A Unicode character can occupy more than one byte in UTF-8. When printing to the screen, MATLAB documents the return value as the number of characters displayed.

fprintf vs sprintf vs disp

FunctionResultBest fit
fprintfWrites formatted text to the screen, stderr, or a fileReports, exports, progress, and controlled output
sprintfReturns formatted text as a character vectorBuild a message, label, or filename for later use
dispDisplays a value and adds a newlineQuick interactive output without format control

sprintf uses the same style of format specification but does not write to a stream:

label = sprintf('Run %03d: %.2f ms', 7, 12.345);
disp(label)

Performance in loops

Formatting and I/O take time. Frequent Command Window output can dominate a short loop and make timing results misleading. Print at intervals, write fewer larger blocks, or move diagnostic output outside the measured section when the individual messages are not required.

for k = 1:nSteps
    state = updateState(state);
    if mod(k, 100) == 0
        fprintf('Completed %d of %d steps\n', k, nSteps);
    end
end

There is no universal slowdown factor: the cost depends on the destination, message size, loop body, buffering, and runtime environment. Measure the actual workload.

MATLAB also accepts GPU-array input to fprintf, but the function does not run on the GPU. Avoid frequent formatted output inside performance-sensitive GPU work because observation can introduce host-side work and synchronization.

Use fprintf for logs, not as a debugger replacement

fprintf is useful when a message must survive after the run: batch progress, a concise result summary, a diagnostic record, or output consumed by another process.

For an interactive bug, MATLAB's debugger is usually more direct. It supports breakpoints, stepping, call-stack navigation, and inspecting values in the current workspace. A conditional breakpoint can stop on the exact iteration you care about without printing thousands of lines.

for k = 1:5000
    T = updateTemperature(T);
end

Set a conditional breakpoint inside the loop, such as k == 3847, or use an error breakpoint when the failure produces an error. Use fprintf when you need a durable text record; use the debugger when you need to pause and inspect program state.

Using fprintf in RunMat

RunMat implements MATLAB-compatible fprintf forms for formatted standard output and file output, including repeated formats and column-order array traversal. RunMat also accepts the stream names "stdout" and "stderr", but those string aliases should not be treated as portable MATLAB syntax.

Before moving a larger script, check the current fprintf built-in reference and test the exact specifiers, input types, file encoding, and error behavior your workload relies on. Compatibility is scoped to documented and tested behavior, not a claim of complete MATLAB parity.

Frequently asked questions

How do I print a newline with fprintf in MATLAB?

Include \n in the format string. fprintf writes exactly the text you specify and does not add a newline automatically.

How do I write to stderr in MATLAB?

Use file identifier 2, for example fprintf(2, 'Warning: %s\n', message). MATLAB reserves 1 for standard output and 2 for standard error.

How do I write formatted text to a file in MATLAB?

Open the file with fopen, check that its file identifier is not -1, pass that identifier to fprintf, and close it with fclose. In a function, onCleanup can ensure the file closes after an error or Ctrl+C.

What is the difference between fprintf and sprintf?

fprintf writes formatted text to the screen, standard error, or a file. sprintf returns formatted text as a character vector instead of writing it.

Why does fprintf print matrix values in the wrong order?

fprintf processes array elements in column order. Transpose a matrix before passing it to a row-oriented format string when you want one output line per original row.

Does fprintf replace the MATLAB debugger?

No. fprintf is useful for progress messages and persistent text logs. MATLAB's debugger is better when you need breakpoints, stepping, the call stack, or workspace inspection.

Sources

  1. MathWorks. "fprintf: Write data to text file." MATLAB documentation for syntax, format operators, array order, stream identifiers, return values, and extended capabilities.

  2. MathWorks. "fopen: Open file or obtain information about open files." MATLAB documentation for permissions, file identifiers, errors, and character encoding.

  3. MathWorks. "onCleanup: Cleanup tasks upon function completion." MATLAB documentation for cleanup behavior on normal and forced function exit.

  4. MathWorks. "Debug Code." MATLAB documentation for interactive debugging tools and debugging functions.

Enjoyed this post? Join the newsletter

Monthly updates on RunMat internals, development, and performance tips.

Use RunMat for free

RunMat is free to use in your browser, on Desktop, or with the CLI.