Exporting Data to Spreadsheets and Text Files Using MATLAB writematrix

Function: writematrix

Exports matrix data to a file.

Syntax

writematrix(A)
writematrix(A, filename)
writematrix(___, Name, Value)

Description

writematrix(A) writes the homogeneous array A to a comma-separated text file. The output filename defaults to the workspace variable name appended with .txt. If the variable name cannot be determined, it saves as matrix.txt. Each column of A corresponds to a column in the output file. Existing files are overwritten.

writematrix(A, filename) writes to a file with the specified name and extension. The file format is determined by the extension:

  • .txt, .dat, or .csv for delimited text files.
  • .xls, .xlsm, or .xlsx for Excel spreadsheets.
  • .xlsb for Excel spreadsheets supported on Windows systems with Excel installed.

writematrix(___, Name, Value) adds optional name-value pair arguments to customize the export process using any of the previous input combinations.

Example 1: Exporting to a Delimited Text File

Generate a numeric matrix and save it as a comma-separated file, then export the same data using a different delimiter.

dataMat = randi(100, 4, 4)
dataMat = 4×4

    32    88    10    16
    74    58    28    31
    11    62    73     5
    53    27     4    49

Save the matrix to a comma-separated file and display its contents:

writematrix(dataMat);
type 'dataMat.txt'
32,88,10,16
74,58,28,31
11,62,73,5
53,27,4,49

Save the same matrix using a tab delimiter:

writematrix(dataMat, 'dataMat_tab.txt', 'Delimiter', 'tab');
type 'dataMat_tab.txt'
32	88	10	16
74	58	28	31
11	62	73	5
53	27	4	49

Example 2: Exporting to a Spreadsheet

Generate a matrix, save it to an Excel file, and read it back to verify.

vals = pascal(4)
vals = 4×4

     1     1     1     1
     1     2     3     4
     1     3     6    10
     1     4    10    20
writematrix(vals, 'vals.xlsx')
readmatrix('vals.xlsx')
ans = 4×4

     1     1     1     1
     1     2     3     4
     1     3     6    10
     1     4    10    20

Example 3: Specifying Sheet and Range in a Spreadsheet

Write a matrix to a specific location within an Excel workbook.

vals = pascal(4);
writematrix(vals, 'vals.xlsx', 'Sheet', 2, 'Range', 'B2:E5')
readmatrix('vals.xlsx', 'Sheet', 2, 'Range', 'B2:E5')
ans = 4×4

     1     1     1     1
     1     2     3     4
     1     3     6    10
     1     4    10    20

Example 4: Appending Data to a Spreadsheet

Append new rows of data below existing data in an Excel sheet.

mat1 = pascal(4);
mat2 = eye(3,4);
writematrix(mat1, 'vals.xlsx')
writematrix(mat2, 'vals.xlsx', 'WriteMode', 'append')
readmatrix('vals.xlsx')
ans = 7×4

     1     1     1     1
     1     2     3     4
     1     3     6    10
     1     4    10    20
     1     0     0     0
     0     1     0     0
     0     0     1     0

Example 5: Appending Data to a Text File

Append rows below existing data in a CSV file.

seq1 = [1 2 3; 4 5 6];
seq2 = [7 8 9];
writematrix(seq1, 'sequences.csv')
writematrix(seq2, 'sequences.csv', 'WriteMode', 'append')
readmatrix('sequences.csv')
ans = 3×3

     1     2     3
     4     5     6
     7     8     9

Example 6: Writing Column Vectors with Headers to Excel

Transpose a row vector to a column, define headers, and export sequentially to an Excel file.

dataSignal = randperm(10, 5); % Generate a 1x5 row vector
[nRows, nCols] = size(dataSignal);
if nRows == 1
    colSignal = dataSignal'; % Convert to column vector
else
    colSignal = dataSignal;
end

targetFile = 'output_metrics.xlsx';
colHeaders = ["MetricA", "MetricB", "MetricC"];

% Write headers to the first row across columns 1 to 3
writematrix(colHeaders, targetFile, 'Range', '1:3');

% Append the column vector below the first column
writematrix(colSignal, targetFile, 'WriteMode', 'append');

Input Parameters

A - Input Data

Matrix to export.

filename - File Name

Character vector or string scalar specifying the destination. It can be a local file name, a full/relative path, or a remote URL (e.g., s3://bucket_name/path/file.xlsx for Amazon S3, wasb://... for Azure, hdfs://... for HDFS). If no extension is provided, .txt is appended. If the file does not exist, it is created. Text files are overwritten, while spreadsheets only update the specified ranges.

Name-Value Arguments

Specify optional comma-separated pairs of Name,Value arguments.

FileType - File Type

'text' or 'spreadsheet'. Use when filename lacks a standard extension.

DateLocale - Locale for Dates

Character vector or string (e.g., 'en_US') defining the locale for writing month/day names in datetime values. Ignored if dates are written in Excel date format.

WriteMode - Write Mode

Specifies the write behavior.

File TypeMode Options
Text'overwrite' (default), 'append'
Spreadsheet'inplace' (default - updates only occupied cells), 'overwritesheet' (clears the target sheet), 'append' (adds rows below existing data), 'replacefile' (deletes other sheets and clears the target sheet)

Delimiter - Field Delimiter

Applicable only to text files. Options: 'comma' (default), 'space', 'tab', 'semi', 'bar'.

QuoteStrings - Text Quoting Indicator

true or false. If true, encloses text in double quotes and escapes existing quotes. If unset, quotes are added dynamically if the delimiter is found within the text.

Encoding - Character Encoding

Default is 'UTF-8'. Other standard schemes like 'ISO-8859-1' can be specified.

Sheet - Target Worksheet

Worksheet name or positive integer index. If the sheet doesn't exist, it is added. Applicable only to spreadsheets.

Range - Target Rectangle

Specifies the starting cell (e.g., 'D2') or a rectangular region (e.g., 'D2:H4'). If the range is smaller than the data, data is truncated; if larger, remaining cells are unmodified. Applicable only to Excel files.

UseExcel - Windows Excel Instance Flag

true or false. Setting to true launches a Windows Excel instance during the write process, enabling support for formats like .xlsb and interactive features like macros.

AutoFitWidth - Auto Adjust Column Width

true (default) or false. Determines if column widths adjust to fit the data.

PreserveFormat - Preserve Cell Formatting

true or false. If false, existing cell formatting (fonts, borders, colors) is stripped. Requires UseExcel to be true to work correctly with datetime data.

Limitations

To use 'PreserveFormat' as true, 'UseExcel' must also be set to true.

Algorithms

writematrix may not preserve exact precision for round-trip read/write operations. Numeric data is written using long g format, and categorical/character data is unquoted. N-dimensional arrays are flattened into 2D. For exact data preservation, save as a MAT-file.

Tags: MATLAB writematrix Excel Export Data Processing Spreadsheet I/O

Posted on Wed, 19 Aug 2026 16:47:07 +0000 by simn_stv