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

fwrite — Write binary data to file identifiers in MATLAB and RunMat.

fwrite writes binary data to a file identifier obtained from fopen. Precision strings, skip values, machine-format overrides, and column-major emission order follow MATLAB semantics. It accepts numeric, logical, and character inputs and returns the count of values written.

Syntax

count = fwrite(fid, data)
count = fwrite(fid, data, precision)
count = fwrite(fid, data, precision, skip)
count = fwrite(fid, data, precision, machinefmt)
count = fwrite(fid, data, precision, skip, machinefmt)

Inputs

NameTypeRequiredDefaultDescription
fidNumericScalarYes—File identifier opened by fopen.
dataAnyYes—Numeric/logical/text payload to write.
precisionStringScalarNo"uint8"Write precision label (for example "uint8", "double").
skipNumericScalarNo0Bytes skipped after each element written.
machinefmtStringScalarNo"native"Machine format label (native/little-endian/big-endian aliases).

Returns

NameTypeDescription
countNumericScalarNumber of elements successfully written.

Errors

IdentifierWhenMessage
RunMat:fwrite:InvalidInputIdentifier, payload, or argument cardinality/type constraints are violated.fwrite: invalid input arguments
RunMat:fwrite:InvalidIdentifierIdentifier does not refer to a writable open file.fwrite: invalid file identifier. Use fopen to generate a valid file ID.
RunMat:fwrite:InvalidOptionPrecision, skip, or machine format options are invalid.fwrite: invalid option configuration
RunMat:fwrite:IoFailureWrite/seek operation fails.fwrite: file write failed
—Internal runtime control-flow conversion fails.fwrite: internal error

How fwrite works

  • count = fwrite(fid, A) converts A to unsigned 8-bit integers and writes one byte per element.
  • count = fwrite(fid, A, precision) converts A to the requested precision before writing. All eight integer input classes retain authoritative values through encoding, including exact int64 and uint64 values above the binary64 exact-integer boundary.
  • count = fwrite(fid, A, precision, skip) skips skip bytes after writing each element. RunMat applies the skip with a file seek, which produces sparse regions when the target position moves beyond the current end.
  • count = fwrite(fid, A, precision, skip, machinefmt) overrides the byte ordering used for the conversion. Supported machine formats are 'native', 'ieee-le', and 'ieee-be'. When omitted, the builtin honours the format recorded by fopen.
  • Column-major ordering matches MATLAB semantics: tensors and character arrays write their first column completely before advancing to the next column. Scalars and vectors behave as 1-by-N matrices.
  • The return value count is the number of elements written, not the number of bytes. A zero-length input produces count == 0.
  • RunMat executes fwrite entirely on the host. Typed integer identifiers and skips, logical/single/resident controls, fread-style source=>output precision, and direct gpuArray data are independently gated RunMat extensions checked before gather or I/O.

Does RunMat run fwrite on the GPU?

fwrite never launches GPU kernels. In runmat compatibility mode, direct GPU data input is accepted as a RunMat extension and gathered to host memory before the write. When a provider is available, the gather occurs via the provider's download path; otherwise the builtin emits an informative error.

GPU memory and residency

RunMat keeps tensors on the GPU while compute stays in fused expressions, but explicit file I/O always happens on the host. In runmat compatibility mode, direct gpuArray data input performs an automatic gather, writes the bytes, and leaves the original value's residency unchanged for the rest of the program.

Examples

Write unsigned bytes with the default precision

fid = fopen('bytes.bin', 'w+b');
count = fwrite(fid, [1 2 3 255]);
fclose(fid);
count

Expected output:

count = 4

Write double-precision values

fid = fopen('values.bin', 'w+b');
data = [1.5 -2.25 42.0];
count = fwrite(fid, data, 'double');
fclose(fid);
count

Expected output:

count = 3

Write 16-bit integers using big-endian byte ordering

fid = fopen('sensor.be', 'w+b', 'ieee-be');
count = fwrite(fid, [258 772], 'uint16');
fclose(fid);
count

Expected output:

count = 2

Insert padding bytes between samples

fid = fopen('spaced.bin', 'w+b');
count = fwrite(fid, [10 20 30], 'uint8', 1);   % skip one byte between elements
fclose(fid);
count

Expected output:

count = 3

Write character data without manual conversions

fid = fopen('greeting.txt', 'w+b');
count = fwrite(fid, 'RunMat!', 'char');
fclose(fid);
count

Expected output:

count = 7

Gather GPU data before writing

fid = fopen('gpu.bin', 'w+b');
G = gpuArray([1 2 3 4]);
count = fwrite(fid, G, 'uint16');
fclose(fid);
count

Expected output:

count = 4

Using fwrite with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how fwrite changes the result.

Run a small fwrite example, explain the result, then change one input and compare the output.

FAQ

What precisions does fwrite support?⌄

RunMat recognises the commonly used MATLAB precisions: double, single, uint8, int8, uint16, int16, uint32, int32, uint64, int64, and char, along with several documented aliases. In runmat mode, matching source=>output forms are an explicitly gated convenience; the compatibility target documents that grammar for fread, not fwrite.

How are values converted before writing?⌄

Numeric inputs are converted to the requested precision using MATLAB-style rounding (to the nearest integer) with saturation to the target range. Logical inputs map true to 1 and false to 0. Character inputs use their Unicode scalar values.

What does the return value represent?⌄

fwrite returns the number of elements successfully written, not the total number of bytes. Multiply by the element size when you need to know the byte count.

Does skip insert bytes into the file?⌄

skip seeks forward after each element is written. When the seek lands beyond the current end of file, the OS creates a sparse region (holes are zero-filled on most platforms). Use skip = 0 (the default) to write densely.

How do machine formats affect the output?⌄

The machine format controls byte ordering for multi-byte precisions. 'native' uses the host endianness, 'ieee-le' forces little-endian ordering, and 'ieee-be' forces big-endian ordering regardless of the host.

Can I write directly to standard output?⌄

Not yet. File identifiers 0, 1, and 2 (stdin, stdout, stderr) are reserved and raise a descriptive error. Use fopen to create a file handle before calling fwrite.

Are GPU tensors supported?⌄

Yes. RunMat gathers GPU tensors to host memory before writing. The gather relies on the active provider; if no provider is registered, an informative error is raised.

Do string arrays insert newline characters?⌄

RunMat joins string-array elements using newline ('\n') separators before writing. This mirrors how MATLAB flattens string arrays to character data for binary I/O.

What happens with NaN or infinite values?⌄

NaN values map to zero for integer precisions and remain NaN for floating-point precisions. Infinite values saturate to the min/max integer representable by the target precision.

Related Io functions

Filetext

fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · 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 fwrite is executed, line by line, in Rust.

  • View the source for fwrite 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 fwrite works
  • Does RunMat run fwrite on the GPU?
  • GPU memory and residency
  • Examples
  • Write unsigned bytes with the default precision
  • Write double-precision values
  • Write 16-bit integers using big-endian byte ordering
  • Insert padding bytes between samples
  • Write character data without manual conversions
  • Gather GPU data before writing
  • Using fwrite 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