writematrix — Write numeric or string matrices to delimited text files with MATLAB-compatible option defaults.
writematrix(A, filename) serializes matrix data to delimited text using MATLAB-compatible delimiter, quoting, newline, and write-mode options.
Syntax
bytesWritten = writematrix(data, filename)
bytesWritten = writematrix(data, filename, name, optionValue)
bytesWritten = writematrix(data, filename, nameValuePairs...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
data | Any | Yes | — | Numeric or string matrix to write. |
filename | StringScalar | Yes | — | Output file path. |
name | StringScalar | Yes | — | Option name. |
optionValue | Any | Yes | — | Value for the preceding option name. |
nameValuePairs... | Any | Variadic | — | Name-value option pairs. |
Returns
| Name | Type | Description |
|---|---|---|
bytesWritten | NumericScalar | Number of bytes written to the destination file. |
Errors
| Identifier | When | Message |
|---|---|---|
| — | Filename argument is missing or name-value options are malformed. | writematrix: invalid argument configuration |
| — | Filename is not a valid scalar path string. | writematrix: invalid filename input |
| — | A provided option value is invalid. | writematrix: invalid option value |
| — | Input data cannot be converted into a supported writematrix matrix form. | writematrix: invalid input data |
| — | Input data has unsupported dimensionality. | writematrix: input must be 2-D |
| — | The destination file cannot be opened or written. | writematrix: file write failed |
How writematrix works
- Accepts real numeric, logical, or string arrays with up to two dimensions (trailing singleton dimensions are ignored). Heterogeneous data requires
writecellinstead. - Default delimiters follow MATLAB: comma for
.csv, tab for.tsv, whitespace for.txtand.dat, and comma for other extensions. Specify'Delimiter', valueto override. 'WriteMode'supports'overwrite'(default) and'append'. Overwrite truncates existing files; append writes new rows to the end without inserting extra delimiters.'QuoteStrings'controls whether text fields are wrapped in double quotes. When enabled (the default) embedded quotes are doubled ("Alice"becomes""Alice"").'DecimalSeparator'swaps the decimal point for locales that require','or other characters. Thousands separators are not inserted automatically, matching MATLAB.'LineEnding'supports'auto'(normalized\nfor cross-platform portability),'unix','pc'/'windows', and'mac'.'FileType'accepts'delimitedtext'or'text'. Spreadsheet output ('spreadsheet') is not yet available and triggers a descriptive error consistent with MATLAB's messaging.- Unsupported options are ignored for forward compatibility. Errors indicate which argument was invalid when the value cannot be interpreted.
Does RunMat run writematrix on the GPU?
writematrix always executes on the host. When the input matrix resides on a GPU, RunMat gathers the array via the active acceleration provider before formatting. No provider-specific hooks or GPU kernels are required, and the result of the write remains a host-side side effect (file on disk). If no provider is registered, the builtin emits the same gather error reported by other residency sinks.
GPU memory and residency
No additional steps are required. writematrix treats GPU arrays as residency sinks: the data is gathered before formatting, ensuring the file on disk reflects host memory. This mirrors MATLAB, where writematrix operates on numeric values regardless of their original residency.
Examples
Save a numeric matrix to a CSV file
A = [1 2 3; 4 5 6];
writematrix(A, "results.csv")Export data with a custom semicolon delimiter
A = [1 2 3; 4 5 6];
writematrix(A, "results.dat", 'Delimiter', ';')Append additional rows to an existing report
writematrix([7 8 9], "report.txt");
writematrix([10 11 12], "report.txt", 'WriteMode', 'append')Write string data with quoting disabled
names = ["Alice" "Bob" "Charlie"];
writematrix(names, "names.csv", 'QuoteStrings', false)Use a European decimal separator and explicit line ending
vals = [12.34; 56.78];
writematrix(vals, "eu.csv", 'DecimalSeparator', ',', 'LineEnding', 'unix')Write GPU-resident data transparently
G = gpuArray(rand(2, 3));
writematrix(G, "gpu_output.csv")Expected output:
% Data is gathered from the GPU automatically and written to disk as 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 heterogenous content (mixed numbers and text) use writecell or writetable.
How are empty matrices handled?⌄
Zero-row or zero-column inputs produce either an empty file or blank line endings per MATLAB's behaviour. The file is still created or truncated according to 'WriteMode'.
Can I write OTA spreadsheet formats like .xlsx?⌄
Not yet. Passing 'FileType','spreadsheet' raises a descriptive error. Use MATLAB's table-based workflows or export delimited text instead.
How are embedded quotes in text fields escaped?⌄
When 'QuoteStrings' is true, embedded double quotes are doubled ("She said ""hi"""), conforming to RFC 4180 and MATLAB's implementation. With quoting disabled, the characters are written verbatim.
What happens if I choose ',' as both delimiter and decimal separator?⌄
RunMat mirrors MATLAB by honouring your request without modification, even though the output may be ambiguous. Choose a different delimiter when writing locale-specific decimals.
Does writematrix change the working directory?⌄
No. Relative paths are resolved against the current MATLAB working directory, and only the target file is touched.
How do I include header rows or variable names?⌄
writematrix focuses on numeric/string matrices. For labelled data use writetable (planned) or prepend header lines manually with fprintf before calling writematrix in 'append' mode.
Related Io functions
Tabular
csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · readmatrix · spreadsheetImportOptions · writecell · xlsread
Repl Fs
addpath · cd · copyfile · delete · dir · exist · fullfile · genpath · getenv · ls · mkdir · movefile · path · pwd · rmdir · rmpath · run · savepath · setenv · tempdir · tempname · uigetfile · uiputfile
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite
Import
Json
Archive
Http
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. 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 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.