RunMat
  • Pricing
RunMat
GitHub
GitHub
Sign inTry in browser
DesktopRuntimePhysicsCADAdministrationAgent

Get RunMat updates

New releases, guides and examples.

Product+
  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download
Math+
  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting
Physics+
  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA
Industries+
  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance
Learn+
  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students
Compare+
  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons
Company+
  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms

Product

  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download

Math

  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting

Physics

  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA

Industries

  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance

Learn

  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students

Compare

  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons

Company

  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms
GitHubXLinkedIn

© Dystr, Inc. · RunMat v0.7.1, Nov 17, 2026

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.

/
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 converts real numeric, logical, or text data to a binary precision and writes it through a file identifier from fopen. Values are emitted in column-major order. The result is a double scalar count of elements, not bytes.

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

fid
Type
NumericScalar
Required
Yes
Description
File identifier opened by fopen.
data
Type
Any
Required
Yes
Description
Numeric/logical/text payload to write.
precision
Type
StringScalar
Required
No
Default
"uint8"
Description
Write precision label (for example "uint8", "double").
skip
Type
NumericScalar
Required
No
Default
0
Description
Bytes skipped after each element written.
machinefmt
Type
StringScalar
Required
No
Default
"native"
Description
Machine format label (native/little-endian/big-endian aliases).
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

count
Type
NumericScalar
Description
Number of elements successfully written.
NameTypeDescription
countNumericScalarNumber of elements successfully written.

Errors

RunMat:fwrite:InvalidInput
When
Identifier, payload, or argument cardinality/type constraints are violated.
Message
fwrite: invalid input arguments
RunMat:fwrite:InvalidIdentifier
When
Identifier does not refer to a writable open file.
Message
fwrite: invalid file identifier. Use fopen to generate a valid file ID.
RunMat:fwrite:InvalidOption
When
Precision, skip, or machine format options are invalid.
Message
fwrite: invalid option configuration
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

Data and precision

count = fwrite(fid, A) writes one unsigned 8-bit value per element. A precision such as 'double', 'single', 'uint16', or 'int64' chooses the target binary representation. count reports elements successfully written, so an empty input returns zero. Exact values from all eight integer input classes remain in integer storage through conversion, including int64 and uint64 values above binary64's exact-integer range. Integer narrowing rounds and saturates; NaN maps to zero for integer output and remains NaN for floating output, while infinities saturate at integer bounds.

Numeric and logical arrays traverse column-first. Character arrays emit Unicode scalar values; string arrays join elements with newline separators before emission. Complex values are not supported. File identifiers 0, 1, and 2 are reserved; use fopen for a writable file handle.

Skip, byte order, and residency

fwrite(fid, A, precision, skip) seeks forward by skip bytes after each element. A seek beyond the end can leave a sparse region, commonly read back as zero-filled bytes. A machine-format argument overrides the format recorded by fopen: 'native', 'ieee-le', and 'ieee-be' select native, little-endian, and big-endian byte ordering for multibyte values.

The write runs on the host and is a fusion boundary. In RunMat mode, resident data and controls are gathered from their owning provider before writing, without changing the caller's original resident value. Integer-class file IDs and skips, logical/single/resident controls, direct GPU data, and fread-style source=>output precision are separately gated RunMat extensions. An unavailable owning provider fails the gather. Browser execution requires an installed filesystem service.

Examples

Write unsigned bytes with the default precision

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

Expected output:

count = 4

Write double-precision values

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

Expected output:

count = 3

Write 16-bit integers with big-endian byte order

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

Expected output:

count = 2

Insert padding between samples

[fid, msg] = fopen('spaced.bin', 'w+b');
assert(fid ~= -1, msg);
count = fwrite(fid, [10 20 30], 'uint8', 1);
fclose(fid);
count

Expected output:

count = 3

Write character data without manual conversion

[fid, msg] = fopen('greeting.txt', 'w+b');
assert(fid ~= -1, msg);
count = fwrite(fid, 'RunMat!', 'char');
fclose(fid);
count

Expected output:

count = 7

Gather GPU data before writing

[fid, msg] = fopen('gpu.bin', 'w+b');
assert(fid ~= -1, msg);
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?⌄

The runtime recognizes double, single, all eight integer widths, and char, with aliases such as float64 and real*8. In RunMat mode, matching source=>output forms are a separately gated convenience; the compatibility target documents that grammar for fread, not fwrite.

How are values converted before writing?⌄

Integer precisions round floating values to the nearest integer and saturate at the target bounds. Logical values become 0 or 1; character inputs use their Unicode scalar values. Exact integer inputs do not pass through a binary64 mirror.

What does the return value represent?⌄

The number of elements written, not bytes. Multiply by the precision's element width to estimate payload bytes.

Does skip insert bytes into the file?⌄

It seeks after each element. A later write beyond the previous end may create a sparse region, commonly read back as zeros.

How do machine formats affect output?⌄

Native uses the host endianness, ieee-le forces little-endian, and ieee-be forces big-endian for multibyte values.

Can I write directly to standard output?⌄

No. IDs 0, 1, and 2 are reserved by this binary file API; open a writable file with fopen.

Are GPU tensors supported?⌄

In RunMat mode, direct resident data gathers from its owning provider for host file writing. If the owner cannot provide the data, the write fails.

Do string arrays insert newlines?⌄

Yes. The runtime joins string-array elements with newline separators before converting characters to the selected binary precision.

What happens with NaN or infinity?⌄

NaN maps to zero for integer precisions and remains NaN for floating precisions; infinities saturate for integer precisions.

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 · 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

Audio

audioinfo · audioread

Io

clc · diary · disp · display · format · input

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

Archive

gunzip · gzip · unzip

Hdf5

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

Import

importdata · textscan

Json

jsondecode · jsonencode

Mat

load · matfile · matlab.io.MatFile.subsasgn · matlab.io.MatFile.subsref · save

Http

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

Source you can read

Every RunMat function's source is public. 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 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.

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
  • Data and precision
  • Skip, byte order, and residency
  • Examples
  • Write unsigned bytes with the default precision
  • Write double-precision values
  • Write 16-bit integers with big-endian byte order
  • Insert padding between samples
  • Write character data without manual conversion
  • Gather GPU data before writing
  • Using fwrite with coding agents
  • FAQ
  • Related Io functions
  • Filetext
  • Net
  • Repl Fs
  • Tabular
  • Audio
  • Io
  • Data
  • Archive
  • Hdf5
  • Import
  • Json
  • Mat
  • Http
  • Source you can read
  • About RunMat