fprintf — Write formatted text to files or standard streams in MATLAB and RunMat.
fprintf formats data using a printf-style template and writes to a file, stdout, or stderr. Supported conversions, repeated formats, and column-major array traversal follow the documented forms; RunMat-specific identifier and format forms are independently gated.
Syntax
count = fprintf(formatSpec, A...)
count = fprintf(fid_or_stream, formatSpec, A...)Inputs
formatSpec- Type
Any- Required
- Yes
- Description
- Format string or character row vector.
A- Type
Any- Required
- Variadic
- Description
- Values consumed by conversion specifiers.
fid_or_stream- Type
Any- Required
- Yes
- Default
1- Description
- Numeric file identifier, or stream label ('stdout'|'stderr').
Returns
count- Type
NumericScalar- Description
- Number of bytes written.
Errors
RunMat:fprintf:InvalidInput- When
- Argument count/type does not satisfy fprintf requirements.
- Message
fprintf: invalid input arguments
RunMat:fprintf:InvalidIdentifier- When
- File identifier is invalid or not writable.
- Message
fprintf: invalid file identifier. Use fopen to generate a valid file ID.
RunMat:fprintf:InvalidFormat- When
- Format string parsing or placeholder consumption fails.
- Message
fprintf: invalid format specification
Formats, values, and byte count
fprintf(formatSpec, A, ...) writes to standard output. fprintf(fid, formatSpec, A, ...) writes to a double file identifier from fopen; identifiers 1 and 2 select stdout and stderr. The return value is a double scalar count of bytes written, which may exceed the character count in multibyte encodings. Omitting the output does not change the write.
The format repeats until flattened arguments are consumed. Numeric, logical, and text arrays are traversed column-first. Character vectors, string scalars, string arrays, and cells containing supported values can contribute formatting arguments. Exact integer values, including wide uint64, are retained for integer conversions; finite floating values that do not fit a signed integer conversion use scientific notation instead of truncation or clamping, retaining the specified flags, width, and precision as a RunMat policy. %e/%E use signed, at-least-two-digit exponents; %g/%G precision counts significant digits and suppresses trailing zeros unless # is present. A sole %s conversion may map valid integer character codes to text. Width and precision star arguments use the same flattened stream. A literal format with extra arguments is an error.
A file uses the encoding recorded by fopen. Explicit ASCII and Latin-1 reject unrepresentable characters; binary/raw and other labels use UTF-8 behavior. Files opened read-only reject writes. File flushing follows the handle and close policy; console buffering belongs to the host.
Compatibility and residency
Double file IDs and numeric streams 1 and 2 are compatible forms. Typed integer, single, and resident file IDs; numeric-code and resident format vectors; and case-insensitive stdout/stderr labels are separate RunMat extensions. Compatibility mode rejects these forms at their gate.
Provider-resident inputs are gathered to host storage before substitution. There is no formatting GPU kernel or fusion path; an unavailable owning provider yields a gather error. The current runtime formats complete host text before writing. Browser execution requires its installed console or filesystem service.
Examples
Write formatted text to a file
[fid, msg] = fopen('report.txt', 'w');
assert(fid ~= -1, msg);
count = fprintf(fid, 'Total: %d (%.2f%%)\n', 42, 87.5);
fclose(fid);
countExpected output:
count = 19Write to standard output
n = 42;
count = fprintf('Processed %d items\n', n);
countExpected output:
Processed 42 itemsWrite to standard error by stream name
iter = 100;
count = fprintf('stderr', 'Warning: iteration limit reached (%d steps)\n', iter);
countExpected output:
Warning: iteration limit reached (100 steps)Format a matrix column-first
A = [1 2 3; 4 5 6];
count = fprintf('%d %d\n', A);
countExpected output:
1 4
2 5
3 6Respect a file's ASCII encoding
[fid, msg] = fopen('ascii.txt', 'w', 'native', 'ascii');
assert(fid ~= -1, msg);
error_id = '';
try
fprintf(fid, 'café\n');
catch err
error_id = err.identifier;
end
close_status = fclose(fid);
assert(strcmp(error_id, 'RunMat:fprintf:EncodeFailed'));
assert(close_status == 0);Format GPU-resident data on the host
G = gpuArray([1.2 3.4 5.6]);
[fid, msg] = fopen('gpu.txt', 'w');
assert(fid ~= -1, msg);
count = fprintf(fid, '%.1f,', G);
fclose(fid);
countExpected output:
count = 12Using fprintf with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how fprintf changes the result.
Run a small fprintf example, explain the result, then change one input and compare the output.
FAQ
Does fprintf count characters or bytes?⌄
Bytes. UTF-8 output may use more than one byte per character.
Can I use stdout or stderr names?⌄
Numeric IDs 1 and 2 are compatible. The case-insensitive stream names are independently gated RunMat conveniences.
What happens with a read-only file?⌄
An invalid-identifier error reports that the file is not open for writing; use a permission containing w, a, or + in fopen.
Which encodings are supported?⌄
UTF-8 is the default; ASCII and Latin-1 are explicit options recorded by fopen. Other labels follow the runtime's UTF-8 fallback.
How are multidimensional arrays handled?⌄
Inputs are flattened in column-major order and the format repeats while values remain.
Does fprintf flush?⌄
It writes through the handle. File data is flushed when the handle is closed; standard streams use host buffering.
What if the format has no conversions?⌄
The literal format is written once; additional formatting arguments are an error.
Are cell arrays supported?⌄
Cells containing supported scalar or text values are flattened column-first before formatting.
Can numeric and text arguments mix?⌄
Yes. Values can be interleaved; star width and precision arguments consume the same flattened stream.
How do I suppress the return value?⌄
Do not assign it. Omission does not change the write.
Related Io functions
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fread · frewind · fwrite · readlines · writelines
Repl Fs
addpath · cd · copyfile · delete · dir · exist · fileattrib · fileparts · filesep · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · memmapfile.subsasgn · memmapfile.subsref · mkdir · movefile · open · opentoline · path · pathsep · pcode · pwd · readstruct · rehash · restoredefaultpath · rmdir · rmpath · run · savepath · setenv · setpref · system · tempdir · tempname · uigetdir · uigetfile · uiputfile · unsetenv · userpath · what · winqueryreg · xmlread · xmlwrite
Tabular
arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · fileDatastore · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · setvaropts · setvartype · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite
Data
commit · data.copy · data.create · data.delete · data.exists · data.export · data.import · data.inspect · data.list · data.move · data.open · DataArray.chunk_shape · DataArray.codec · DataArray.dtype · DataArray.fill · DataArray.name · DataArray.rank · DataArray.read · DataArray.resize · DataArray.shape · DataArray.write · Dataset.array · Dataset.arrays · Dataset.attrs · Dataset.begin · Dataset.get_attr · Dataset.has_array · Dataset.id · Dataset.path · Dataset.refresh · Dataset.set_attr · Dataset.set_attrs · Dataset.snapshot · Dataset.version · DataTransaction.abort · DataTransaction.commit · DataTransaction.create_array · DataTransaction.delete_array · DataTransaction.fill · DataTransaction.id · DataTransaction.resize · DataTransaction.set_attr · DataTransaction.set_attrs · DataTransaction.status · DataTransaction.write
Import
Json
Source you can read
Every RunMat function's source is public. Read exactly how fprintf is executed, line by line, in Rust.
- View the source for fprintf in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.