RunMat
GitHub

fprintf — Write formatted text to files or standard streams in MATLAB and RunMat.

fprintf formats data using a printf-style template and writes the result to a file, stdout, or stderr. Format repetition, column-major traversal of array inputs, and supported conversion specifiers follow MATLAB semantics.

Syntax

count = fprintf(formatSpec, A...)
count = fprintf(fid_or_stream, formatSpec, A...)

Inputs

NameTypeRequiredDefaultDescription
formatSpecAnyYesFormat string or character row vector.
AAnyVariadicValues consumed by conversion specifiers.
fid_or_streamAnyYes1Numeric file identifier, or stream label ('stdout'|'stderr').

Returns

NameTypeDescription
countNumericScalarNumber of bytes written.

Errors

IdentifierWhenMessage
RunMat:fprintf:InvalidInputArgument count/type does not satisfy fprintf requirements.fprintf: invalid input arguments
RunMat:fprintf:InvalidIdentifierFile identifier is invalid or not writable.fprintf: invalid file identifier. Use fopen to generate a valid file ID.
RunMat:fprintf:InvalidFormatFormat string parsing or placeholder consumption fails.fprintf: invalid format specification

How fprintf works

  • fprintf(formatSpec, A, ...) writes to standard output. The format repeats automatically until every element from the argument list has been consumed, traversing arrays in column-major order.
  • fprintf(fid, formatSpec, A, ...) writes to a file identifier returned by fopen. Identifiers 1/"stdout" and 2/"stderr" refer to the process streams. Identifiers must be finite, non-negative integers.
  • The return value is the number of bytes written as a double scalar. Omitting the output argument discards it without affecting the write.
  • Text arguments (character vectors, string scalars, string arrays, cell arrays of text) are expanded in column-major order, matching MATLAB's behaviour.
  • Numeric arrays (double, integer, logical, or gpuArray) are flattened column-first and substituted element-by-element into the format string. Star (*) width and precision arguments are also drawn from the flattened stream.
  • The text encoding recorded by fopen is honoured. ASCII and Latin-1 encodings raise descriptive errors when characters cannot be represented. Binary/RAW encodings treat the output as UTF-8, mirroring MATLAB's default on modern systems.
  • Arguments that reside on the GPU are gathered to the host before formatting. Formatting itself is always executed on the CPU.

Does RunMat run fprintf on the GPU?

fprintf is a residency sink. Any argument containing gpuArray data is gathered via the active acceleration provider before formatting. No GPU kernels are launched. When no provider is registered, the builtin raises the same descriptive error used by other sinks (gather: no acceleration provider registered).

GPU memory and residency

You can pass gpuArray inputs directly—fprintf gathers them back to host memory before formatting. No provider-specific hooks are required and outputs always reside on the CPU. This mirrors MATLAB, where explicit gather calls are unnecessary when writing to files or console streams.

Examples

Write Formatted Text To A File

[fid, msg] = fopen('report.txt', 'w');
assert(fid ~= -1, msg);
fprintf(fid, 'Total: %d (%.2f%%)\n', 42, 87.5);
fclose(fid)

Use Standard Output Without An Explicit File Identifier

n = 42;
fprintf('Processed %d items\n', n)

Write To Standard Error Using The Stream Name

iter = 100;
fprintf('stderr', 'Warning: iteration limit reached (%d steps)\n', iter)

Format A Matrix In Column-Major Order

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

Respect File Encoding Constraints

[fid, msg] = fopen('ascii.txt', 'w', 'native', 'ascii');
if fid == -1, error(msg); end
try
    fprintf(fid, 'café\n');
catch err
    disp(err.message);
end
fclose(fid)

Format GPU-Resident Data Transparently

G = gpuArray([1.2 3.4 5.6]);
[fid, msg] = fopen('gpu.txt', 'w');
assert(fid ~= -1, msg);
fprintf(fid, '%.1f,', G);
fclose(fid)

Using 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 return the number of characters or bytes?

It returns the number of bytes written. This may differ from the number of characters when using multi-byte encodings such as UTF-8.

Can I use 'stdout' or 'stderr' instead of numeric identifiers?

Yes. The strings 'stdout' and 'stderr' (any case) map to identifiers 1 and 2 respectively, matching MATLAB.

What happens if the file was opened read-only?

fprintf raises fprintf: file is not open for writing. Ensure the permission string passed to fopen includes 'w', 'a', or '+'.

Which encodings are supported?

fprintf honours the encoding recorded by fopen. UTF-8 (default), ASCII, and Latin-1 are supported explicitly. Other labels fall back to UTF-8 behaviour.

How are multi-dimensional arrays handled?

Arguments are flattened in column-major order. The format string repeats until every element has been consumed, just like MATLAB.

Does fprintf flush the stream?

The builtin delegates to Rust's buffered writers. Files are flushed when closed; standard streams inherit the host buffering policy.

What if the format string contains no conversions?

Literal format strings are written once. Supplying additional arguments raises fprintf: formatSpec contains no conversion specifiers but additional arguments were supplied.

Are cell arrays supported?

Yes. Cell arrays containing supported scalar or text values are flattened in column-major order before formatting.

Can I mix numeric and text arguments?

Absolutely. Numeric, logical, and text inputs can be interleaved. Star width/precision arguments use the same flattened stream.

How do I suppress the return value?

Ignore it, just as in MATLAB. Omitting the output argument does not change the write behaviour.

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how fprintf is executed, line by line, in Rust.

About RunMat

RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.