fread — Read binary data from file identifiers in MATLAB and RunMat.
fread reads binary data from a file identifier returned by fopen. Size, precision, skip, and machine-format arguments follow MATLAB semantics, and file position advances accordingly. Optional second output returns the number of elements successfully read.
Syntax
data = fread(fid)
data = fread(fid, size)
data = fread(fid, size, precision)
data = fread(fid, size, precision, skip)
data = fread(fid, size, precision, skip, machinefmt)
data = fread(fid, precision)All supported fread forms
data = fread(fid)
data = fread(fid, size)
data = fread(fid, size, precision)
data = fread(fid, size, precision, skip)
data = fread(fid, size, precision, skip, machinefmt)
data = fread(fid, precision)
data = fread(fid, precision, skip)
data = fread(fid, precision, machinefmt)
data = fread(fid, precision, skip, machinefmt)
data = fread(fid, ..., "like", prototype)
[data, count] = fread(...)Inputs
fid- Type
NumericScalar- Required
- Yes
- Description
- File identifier opened by fopen.
size- Type
Any- Required
- No
- Default
"inf"- Description
- Element count or size vector ([m n]); supports "inf".
precision- Type
StringScalar- Required
- No
- Default
"uint8=>double"- Description
- Read precision label (for example "double", "uint8", "*char").
precision- Type
StringScalar- Required
- No
- Default
"double"- Description
- Read precision label (for example "double", "uint8", "*char").
skip- Type
NumericScalar- Required
- No
- Default
0- Description
- Bytes skipped after each element read.
machinefmt- Type
StringScalar- Required
- No
- Default
"native"- Description
- Machine format label (native/little-endian/big-endian aliases).
precision- Type
StringScalar- Required
- No
- Default
"double"- Description
- Read precision label when size is omitted.
arg- Type
Any- Required
- Variadic
- Description
- Positional fread arguments before the like clause.
name- Type
PropertyName- Required
- No
- Default
"like"- Description
- Prototype keyword; currently only 'like'.
prototype- Type
Any- Required
- No
- Description
- Prototype value controlling output class/residency.
Returns
data- Type
Any- Description
- Read data as numeric tensor or character array depending on precision.
count- Type
NumericScalar- Description
- Number of source elements actually read, excluding padding.
Returned values from fread depend on how many outputs the caller requests.
Errors
RunMat:fread:InvalidInput- When
- Identifier/argument cardinality/type constraints are violated.
- Message
fread: invalid input arguments
RunMat:fread:InvalidIdentifier- When
- Identifier does not refer to a readable open file.
- Message
fread: invalid file identifier. Use fopen to generate a valid file ID.
RunMat:fread:InvalidOption- When
- Precision, skip, machine format, or like option values are invalid.
- Message
fread: invalid option configuration
Read sizes and result geometry
A = fread(fid) reads uint8 source values to the end of the file and returns a double column vector, including a 0-by-1 column for an empty read.
A = fread(fid, sizeA) reads at most prod(sizeA) elements, filling the result in column-major order. Use [m n] to request a matrix or [m Inf] to keep filling columns until EOF.
A = fread(fid, precision) controls how many bytes each element consumes and how the result is typed. RunMat supports the common precisions from MATLAB: double, single, uint8, int8, uint16, int16, uint32, int32, uint64, int64, and char. When no output class is specified, data is converted to double; char (and *char) return a MATLAB-style character array.
Precision, byte order, and skipping
The char source decodes using the encoding recorded by fopen, rather than acting as a uint8 alias. Character geometry and counts are UTF-16 code units: a supplementary character occupies two units. Limited reads retain the decoder and any pending second unit with the exact file handle. Numeric reads and explicit seeks reset that decoding state; position queries do not. Numeric sources such as uint16=>char instead preserve each checked value in the range 0 through 65535, including raw surrogate units. Malformed encoded text is an error, not replacement text.
A = fread(fid, sizeA, precision, skip, machinefmt) honours optional byte skipping and machine-format overrides ('native', 'ieee-le', 'ieee-be'). The machine format defaults to the value recorded by fopen.
[A, count] = fread(...) returns the number of elements successfully read before encountering EOF.
If MATLAB requests more elements than available, fread pads matrix outputs with zeros (or '\0' for character data) to satisfy the requested dimensions; the count output always reflects the number of real elements read from the file.
Compatibility and residency
In runmat compatibility mode, A = fread(___, 'like', prototype) is a RunMat extension that matches the residency and logical or numeric flavour of prototype. All eight typed integer prototype classes determine exact saturating output storage. GPU prototypes upload through their actual owning provider after pre-read metadata validation, while logical prototypes convert the output using the ordinary non-zero rule. Character precision requires a character prototype, and character prototypes require character precision; invalid pairings reject before file access.
RunMat executes the builtin entirely on the host CPU. Typed integer file identifiers, sizes, and skips are independent RunMat extensions, as are logical, single, and provider-resident controls; all extension policy is checked before gather or I/O.
fread is a host-only operation. In runmat compatibility mode, independently gated resident controls gather before host I/O, and the separately gated 'like' form can upload the result to a GPU prototype. File handles remain in the shared host registry.
The RunMat-only 'like' form uploads through the prototype's exact owning provider. A missing or malformed owner contract rejects before reading rather than silently returning host data.
Examples
Reading double-precision values from a binary file
[fid, msg] = fopen('numbers.bin', 'w+b');
assert(fid ~= -1, msg);
fwrite(fid, [1 2 3], 'double');
frewind(fid);
[values, count] = fread(fid, 3, 'double');
fclose(fid);
valuesExpected output:
values = [1; 2; 3]Reading bytes with a specific element count
[fid, msg] = fopen('payload.bin', 'w+b');
assert(fid ~= -1, msg);
fwrite(fid, uint8(1:6), 'uint8');
frewind(fid);
[bytes, count] = fread(fid, 4, 'uint8');
fclose(fid);
bytesExpected output:
bytes = [1; 2; 3; 4]Loading a two-dimensional block of uint8 data
[fid, msg] = fopen('frame.bin', 'w+b');
assert(fid ~= -1, msg);
payload = uint8(reshape(1:12, 3, 4));
fwrite(fid, payload, 'uint8');
frewind(fid);
[frame, count] = fread(fid, [3 4], 'uint8');
fclose(fid);
frameExpected output:
frame = [1 4 7 10; 2 5 8 11; 3 6 9 12]Reading characters using the *char precision form
[fid, msg] = fopen('message.txt', 'w+b');
assert(fid ~= -1, msg);
fwrite(fid, 'RunMat', 'char');
frewind(fid);
[text, count] = fread(fid, '*char');
fclose(fid);
textExpected output:
text = RunMatSkipping bytes between samples
[fid, msg] = fopen('interleaved.bin', 'w+b');
assert(fid ~= -1, msg);
fwrite(fid, uint8(1:12), 'uint8');
frewind(fid);
[every_other, count] = fread(fid, 5, 'uint8', 1);
fclose(fid);
every_otherExpected output:
every_other = [1; 3; 5; 7; 9]Respecting big-endian machine formats
[fid, msg] = fopen('sensors.be', 'w+b', 'ieee-be');
assert(fid ~= -1, msg);
fwrite(fid, uint16([258 772]), 'uint16');
frewind(fid);
[values, count] = fread(fid, [2 1], 'uint16');
fclose(fid);
valuesExpected output:
values = [258; 772]Matching GPU residency with 'like'
[fid, msg] = fopen('samples.bin', 'w+b');
assert(fid ~= -1, msg);
fwrite(fid, [2.5 4.5 6.5 8.5], 'double');
frewind(fid);
prototype = gpuArray.zeros(4, 1);
[values, count] = fread(fid, 4, 'double', 'like', prototype);
fclose(fid);
valuesExpected output:
values = 4x1 gpuArrayUsing fread with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how fread changes the result.
Run a small fread example, explain the result, then change one input and compare the output.
FAQ
What precision strings are supported?⌄
RunMat implements the commonly used MATLAB precisions: double, single, uint8, int8, uint16, int16, uint32, int32, uint64, int64, and char. The short form *char is also recognised. When an output class is not specified explicitly (with => or the *class syntax), the result is converted to double precision.
How are partial reads handled?⌄
fread stops when it encounters EOF. Matrices requested with [m n] are padded with zeros (or '\0') when the file does not contain enough elements to fill every column. The count output records the number of real elements read before padding.
How do size arguments work?⌄
Pass a scalar N to request a column vector with up to N elements, [M N] to request a matrix with M rows and N columns, or [M Inf] to keep reading additional columns until EOF. Omitting the size argument is equivalent to using Inf (read everything).
How does the skip parameter behave?⌄
skip is a non-negative byte count applied after each complete precision repeat block (n*source, or one element by default). Numeric source widths are fixed; encoded character source widths depend on the actual file encoding. Skipped bytes are not decoded. A nonzero byte skip resets pending decoding state at the resulting physical offset, like an explicit seek.
What does the 'like' prototype control?⌄
The 'like', prototype pair matches the output residency and high-level type of prototype. All eight typed integer classes select exact saturating output storage. A GPU tensor returns through its owning provider, a logical prototype applies the non-zero rule, and only a character prototype may accompany character output precision.
Which machine formats are supported?⌄
The builtin recognises 'native', 'ieee-le', and 'ieee-be' (including their MATLAB aliases such as 'little-endian', 'pc', 'big-endian', and 'mac'). Unsupported formats ('vaxd', 'cray', etc.) raise descriptive errors.
Can fread operate on standard input?⌄
Standard input/output/error identifiers (0, 1, 2) are currently not supported by RunMat's fread. Open files explicitly with fopen before calling fread.
Related Io functions
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · frewind · fwrite · 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 fread is executed, line by line, in Rust.
- View the source for fread 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.