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).
Returns
count- Type
NumericScalar- Description
- Number 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
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);
countExpected output:
count = 4Write 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);
countExpected output:
count = 3Write 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);
countExpected output:
count = 2Insert padding between samples
[fid, msg] = fopen('spaced.bin', 'w+b');
assert(fid ~= -1, msg);
count = fwrite(fid, [10 20 30], 'uint8', 1);
fclose(fid);
countExpected output:
count = 3Write character data without manual conversion
[fid, msg] = fopen('greeting.txt', 'w+b');
assert(fid ~= -1, msg);
count = fwrite(fid, 'RunMat!', 'char');
fclose(fid);
countExpected output:
count = 7Gather 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);
countExpected output:
count = 4Using 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
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 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.