writematrix — Write numeric or string matrices to delimited text files.
writematrix(A, filename) serializes a numeric or string matrix to a delimited text file. Native integer matrices retain their exact decimal values.
Syntax
writematrix(data, filename)
writematrix(data, filename, name, optionValue)
writematrix(data, filename, nameValuePairs...)
bytes = writematrix(data, filename)
bytes = writematrix(data, filename, name, optionValue)
bytes = writematrix(data, filename, nameValuePairs...)Inputs
data- Type
Any- Required
- Yes
- Description
- Numeric or string matrix to write.
filename- Type
StringScalar- Required
- Yes
- Description
- Output file path.
name- Type
StringScalar- Required
- Yes
- Description
- Option name.
optionValue- Type
Any- Required
- Yes
- Description
- Value for the preceding option name.
nameValuePairs...- Type
Any- Required
- Variadic
- Description
- Name-value option pairs.
Returns
bytes- Type
NumericScalar- Description
- RunMat-only bytes-written output.
Errors
- When
- Filename argument is missing or name-value options are malformed.
- Message
writematrix: invalid argument configuration
- When
- Filename is not a valid scalar path string.
- Message
writematrix: invalid filename input
- When
- A provided option value is invalid.
- Message
writematrix: invalid option value
Data and text format
Delimited numeric text uses general formatting with 15 significant digits for double storage and 7 for single storage. Logical fields use 1 or 0; typed integers retain exact decimal values.
Accepts real numeric, logical, or string arrays up to two dimensions; trailing singleton dimensions are ignored. Heterogeneous data requires writecell. Sparse and complex inputs are rejected.
Default delimiters are comma for .csv, tab for .tsv, whitespace for .txt and .dat, and comma for other extensions. 'Delimiter', value overrides this choice.
'WriteMode' accepts 'overwrite' (default) or 'append'. Overwrite truncates existing files; append writes new rows without extra delimiters.
'QuoteStrings' accepts 'minimal' (default), 'all', or 'none'. Minimal quoting protects fields containing the delimiter, a double quote, or a line break. Quoted embedded double quotes are doubled; 'none' writes text verbatim.
RunMat mode additionally accepts logical or numeric zero/one aliases for 'QuoteStrings', 'DecimalSeparator' and 'LineEnding' text-format options, and a bytes-written output. If delimiter and decimal separator are both commas, the ambiguous result is emitted as requested.
'FileType' accepts 'delimitedtext' or 'text'. Spreadsheet output ('spreadsheet', including .xlsx) is not implemented and produces an option error; use delimited text or table workflows.
Zero-row or zero-column inputs create or truncate the file according to 'WriteMode'; a nonzero row count with zero columns emits blank line endings.
Relative paths resolve against the current RunMat directory. writematrix does not change that directory and touches only the destination. Use writetable for variable names or headers.
Residency, ownership and execution
This is a host file-I/O sink and fusion boundary. Automatically resident values gather through their owning provider; direct explicit gpuArray input is a named RunMat extension, admitted before readback. No device kernel or device-resident output is advertised.
The selected filesystem provider, relative working directory and advertised lease are captured before awaited operand preparation and retained through writing. Cancellation or failure can leave partial bytes, including after an overwrite truncates the destination. Large matrices and formatted text consume host memory.
The original example programs and captions are retained here. The runnable gallery below uses isolated destination fixtures and assertions:
Historical example 1 (Save a numeric matrix to a CSV file):
A = [1 2 3; 4 5 6];
writematrix(A, "results.csv")
Historical example 2 (Export data with a custom semicolon delimiter):
A = [1 2 3; 4 5 6];
writematrix(A, "results.dat", 'Delimiter', ';')
Historical example 3 (Append additional rows to an existing report):
writematrix([7 8 9], "report.txt");
writematrix([10 11 12], "report.txt", 'WriteMode', 'append')
Historical example 4 (Write string data without quoting):
names = ["Alice" "Bob" "Charlie"];
writematrix(names, "names.csv", 'QuoteStrings', 'none')
Historical example 5 (Use RunMat text-format options):
vals = [12.34; 56.78];
writematrix(vals, "eu.csv", 'DecimalSeparator', ',', 'LineEnding', 'unix')
Historical example 6 (Capture the RunMat bytes-written output):
bytes = writematrix(uint64([1 2 3]), "values.csv")
Displayed output: % Requires RunMat language extensions.
Examples
Save a numeric matrix to a CSV file
A = [1 2 3;4 5 6];
writematrix(A,'results.csv');
contents = fileread('results.csv')Export data with a custom semicolon delimiter
A = [1 2 3;4 5 6];
writematrix(A,'results.dat','Delimiter',';');
contents = fileread('results.dat')Append additional rows to an existing report
writematrix([10 11 12],'report.txt','WriteMode','append');
contents = fileread('report.txt')Write string data without quoting
names = ["Alice" "Bob" "Charlie"];
writematrix(names,'names.csv','QuoteStrings','none');
contents = fileread('names.csv')Use RunMat text-format options
vals = [12.34;56.78];
writematrix(vals,'eu.csv','DecimalSeparator',',','LineEnding','unix');
contents = fileread('eu.csv')Capture the RunMat bytes-written output
bytes = writematrix(uint64([1 2 3]),'values.csv');
contents = fileread('values.csv')Using writematrix with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how writematrix changes the result.
Run a small writematrix example, explain the result, then change one input and compare the output.
FAQ
Which data types does writematrix support?⌄
Real numeric, logical, and string arrays up to two dimensions. For heterogeneous content use writecell or writetable.
How are empty matrices handled?⌄
Zero-row or zero-column inputs create or truncate the file under 'WriteMode'; rows with no columns produce blank line endings.
Can I write OTA spreadsheet formats like .xlsx?⌄
Not yet. 'FileType','spreadsheet' raises an option error. Export delimited text instead.
How are embedded quotes in text fields escaped?⌄
With 'minimal' or 'all', embedded double quotes are doubled; 'none' writes them verbatim.
What happens if I choose ',' as both delimiter and decimal separator?⌄
RunMat mode honours the request even though the output may be ambiguous; choose different separators for interchange.
Does writematrix change the working directory?⌄
No. Relative paths use the current RunMat directory; the selected destination is written.
How do I include header rows or variable names?⌄
Use writetable for named variables; writematrix focuses on matrices.
Related Io functions
Tabular
arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · fileDatastore · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · setvaropts · setvartype · spreadsheetImportOptions · writecell · writetable · writetimetable · xlsread · xlswrite
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
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
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite · readlines · writelines
Import
Json
Related guides
Source you can read
Every RunMat function's source is public. Read exactly how writematrix is executed, line by line, in Rust.
- View the source for writematrix 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.