RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact

Explore

  • RunMat for academia
  • RunMat vs MATLAB Online
  • Benchmarks

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

RunMat™ is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

LicensePrivacy
/
See all docs
Builtin Reference
    • fclose
    • feof
    • fgetl
    • fgets
    • fileread
    • filewrite
    • fopen
    • fprintf
    • fread
    • frewind
    • fwrite
    • readlines
    • writelines

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
formatSpecAnyYes—Format string or character row vector.
AAnyVariadic—Values 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
RunMat:fprintf:EncodeFailedRendered text cannot be encoded for destination stream/file encoding.fprintf: failed to encode output
RunMat:fprintf:IoFailureWrite to target stream/file fails.fprintf: write failed
—Internal runtime control-flow or conversion fails.fprintf: internal error

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 double file identifier returned by fopen; numeric identifiers 1 and 2 select stdout and stderr. Typed integer, single, and resident identifiers are independently gated RunMat extensions. Host numeric format tensors (double, single, or integer) and provider-resident format vectors are separately gated before gathering; integer format tensors retain an additional integer-specific policy marker.
  • 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, all eight integer classes, logical, or gpuArray) are traversed column-first. Integer %d, %i, %u, %o, %x, and %X conversion retains authoritative values, including wide uint64; a sole %s conversion maps valid integer character codes to text.
  • 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?⌄

The numeric identifiers 1 and 2 are MATLAB-compatible. The case-insensitive strings 'stdout' and 'stderr' are an independently gated RunMat convenience rather than a documented form.

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.

Related Io functions

Filetext

fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fread · frewind · fwrite · readlines · writelines

Net

accept · read · readline · tcpclient · tcpserver · write

Repl Fs

addpath · cd · copyfile · delete · dir · exist · fileattrib · fileparts · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · 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 · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite

Audio

audioinfo · audioread

Io

clc · diary · disp · display · format · input

Archive

gunzip · gzip · unzip

Hdf5

h5disp · h5info · h5read · h5write · h5writeatt · hdf5info · hdf5read · hdf5write

Import

importdata · textscan

Json

jsondecode · jsonencode

Mat

load · matfile · save

Http

sendmail · urldecode · urlencode · weboptions · webread · websave · webwrite

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. 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 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.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • How fprintf works
  • Does RunMat run fprintf on the GPU?
  • GPU memory and residency
  • Examples
  • Write Formatted Text To A File
  • Use Standard Output Without An Explicit File Identifier
  • Write To Standard Error Using The Stream Name
  • Format A Matrix In Column-Major Order
  • Respect File Encoding Constraints
  • Format GPU-Resident Data Transparently
  • Using fprintf with coding agents
  • FAQ
  • Related Io functions
  • Filetext
  • Net
  • Repl Fs
  • Tabular
  • Audio
  • Io
  • Archive
  • Hdf5
  • Import
  • Json
  • Mat
  • Http
  • Open-source implementation
  • About RunMat