Kahibaro
Discord Login Register

Exporting Data to Files

Saving Data from MATLAB

In many workflows you will eventually want to move results out of MATLAB and into files that other programs can read. Exporting data is the process of taking variables that exist in memory and writing them to files on disk in a chosen format. This chapter focuses on exporting to non MAT formats, since MAT files and importing external data are covered separately.

You will see that the basic ideas are always similar. You choose what to export, choose a file format, choose a filename and folder, then call an appropriate export function or use an interactive tool.

Choosing What and How to Export

Before you export, clarify two things. First, decide which variables or parts of variables you actually need. For example, you may only need a few columns of a larger matrix, or a subset of rows from a table. You can use indexing to create a smaller variable, such as dataToSave = bigData(:, 1:3);, then export that.

Second, decide the file format based on what will read the data. Spreadsheets such as Excel work well with text or CSV files. Other programming languages can usually read CSV and simple text formats. Images and audio require specialized formats and functions that are covered elsewhere in this course.

For generic numeric and tabular data, the most common export targets for beginners are plain text files and CSV files. MATLAB provides different functions for these tasks, and these have different levels of convenience and control.

Saving Numeric Data with `save` in Text Form

The save function is primarily used for MAT files, but it can also write numeric arrays to simple text files. When used in text mode, it writes only numeric values in ASCII form, without variable names or headers.

For example, if you have a numeric matrix A, you can write it to a text file with

matlab
save('myData.txt', 'A', '-ascii');

This creates myData.txt in the current folder. Each row of A becomes a line in the file, and values are separated by spaces. Other programs can read this file as generic numeric text. You can change the precision and spacing by adding options such as -ascii -tabs or specifying -double or -single. Since this is low level and less flexible for non numeric data, beginners usually prefer higher level functions for CSV and mixed content.

Remember that this approach does not store variable names or column labels. If you need column headers, you should use table based exports or write custom text with more flexible functions.

Exporting Tables and Timetables with `writetable`

When you work with tables or timetables, writetable is often the most convenient export function. Tables can hold different data types in each column, along with useful metadata such as variable names. writetable converts this structured information into external formats in a straightforward way.

Suppose you have a table T with columns and row names. To write it as a CSV file for use in a spreadsheet or another program, use

matlab
writetable(T, 'results.csv');

By default, this writes the variable names from T as the first row in the file, which acts as a header. Each row of the table becomes one line in the CSV. You can choose different separators and file types with the FileType and Delimiter options. For example, to use a tab delimited text file instead of comma separated values, call

matlab
writetable(T, 'results.txt', 'Delimiter', '\t');

Row names in tables are not written by default. If your table uses row names and you want them included as the first column, set the WriteRowNames parameter to true:

matlab
writetable(T, 'results_with_rows.csv', 'WriteRowNames', true);

If you later import the file, you can reconstruct the table including these names. The handling of dates, times, and categorical variables within tables is usually automatic, with MATLAB choosing appropriate textual representations.

You can also export tables to Excel specific formats, but that is treated in the chapter about importing and working with spreadsheets. In the context of generic file exports, it is important to know that writetable always writes out the entire table unless you export a subset such as T(:, 1:3) or a filtered version.

Writing Arrays and Cell Arrays with `writematrix` and `writecell`

For numeric arrays that are not tables, writematrix offers a simple way to create CSV or text files. The simplest call uses only the matrix and a filename:

matlab
writematrix(A, 'matrix.csv');

In this case each row of A becomes a line in the file, and values in each row are separated by commas. You can control the delimiter and file type similarly to writetable:

matlab
writematrix(A, 'matrix_tab.txt', 'Delimiter', '\t');

writematrix is intended for numeric and string array data without column headers. If you need headers, use a table and writetable, or write the header line manually before you write the data.

When your data is stored in a cell array, for example when you have a mixture of numbers and text, writecell is the appropriate function. For instance, if C is a cell array where each row represents a record and columns include both text and numbers, you can export with

matlab
writecell(C, 'mixedData.csv');

Each cell element is converted to text in the output file, which is useful for general tabular data that is not neatly represented as a numeric matrix. The options for delimiters and file types are similar to those of writematrix and writetable.

Because cell arrays can contain arbitrary content, you should make sure that each element converts sensibly to text. If you have cells that hold nested arrays or complex structures, you may need to convert them explicitly to strings before exporting.

Using `dlmwrite` and Related Functions for Delimited Text

Some older MATLAB code uses dlmwrite for writing delimited numeric data. While newer functions are recommended, you may encounter it and it can still be useful for simple tasks. dlmwrite takes a numeric matrix and writes it to a text file with a specified delimiter.

For example, to create a semicolon separated file of numeric data, you might write

matlab
dlmwrite('data_semicolon.txt', A, 'delimiter', ';');

You can also control precision and numeric format. However, compared to writematrix and writetable, dlmwrite does not handle mixed or non numeric data and has fewer conveniences for headers. For new code that you write, prefer the more modern functions unless you have a specific reason to stay consistent with older scripts.

Controlling File Locations and Overwriting

When you supply a filename such as 'results.csv' without a folder path, MATLAB writes the file into the current folder. To write into a particular subfolder or some other location, include the path in the filename, for example

matlab
writetable(T, 'C:\data\experiment\results.csv');

On different operating systems, use the appropriate file separators, or use the fullfile function to construct paths. For instance,

matlab
folder = 'C:\data\experiment';
file = 'results.csv';
filename = fullfile(folder, file);
writetable(T, filename);

If a file with the same name already exists, these export functions will overwrite it without asking. To avoid accidental overwrites, you can check for existence with exist(filename, 'file') before writing, and choose a new name or ask the user what to do.

Relative paths, such as 'subfolder/results.csv', are interpreted with respect to the current folder. If you are unsure where MATLAB will create the file, check the Current Folder panel or verify with pwd to see the current working directory.

Simple Text Output with `fprintf`

Sometimes you need full control over the exact text format. In that case, you can use file I/O functions such as fopen, fprintf, and fclose to write text files manually. The typical pattern is to open a file for writing, write formatted lines in a loop or vectorized call, then close the file.

For example, to write a two column numeric matrix A with a specific numeric format, you might use

matlab
fid = fopen('formatted.txt', 'w');
fprintf(fid, '%.3f, %.3f\n', A.');
fclose(fid);

The format string '%.3f, %.3f\n' tells fprintf to write two floating point numbers with three decimal places, separated by a comma, then a newline. Transposing A with A.' makes the data match the column by column reading behavior of fprintf.

This approach is more work than calling writematrix or writetable, but it gives you precise control over spacing, signs, decimal places, and the inclusion of extra text or special markers. It is useful when you must match a specific file format requirement from another tool.

Interactive Export with the Import Tool

Although the Import Tool is usually thought of for reading data, it can also help with exporting. After you import data into MATLAB and possibly clean or rearrange it, the tool allows you to save the processed data back out in different formats. For beginners, this interactive approach can be more intuitive than writing code.

You can launch the Import Tool by double clicking a file in the Current Folder panel. Once you have manipulated the dataset, you can use the tool to export it, either to workspace variables or to new text or spreadsheet files. This is particularly handy when you are still learning the export functions and want to experiment with different formats without writing code.

Later, as your needs become more automated, you can replicate the same behavior using script based exports like writetable and writematrix.

Verifying Exported Files

After exporting, it is good practice to verify that the file looks as expected. You can do this by opening the file in a text editor or spreadsheet application, or by re importing it into MATLAB with the appropriate import function.

If you see unexpected characters, wrong delimiters, corrupted accents, or misaligned columns, adjust the export settings. For example, change the delimiter, adjust numeric precision, or include or exclude headers. With experience, you will develop a sense for how different export options affect the file structure.

Always consider who or what will read your exported file. A simple, well structured file that matches the expectations of the next tool in your workflow will save you time and confusion later.

Key points to remember:
Use writetable for tables and timetables, and writematrix or writecell for plain arrays and cell arrays.
The save function in text mode writes numeric arrays without headers and is less flexible than table based exports.
Including full paths in filenames controls where files are written, and existing files are overwritten without warning.
Use formatted text output with fprintf when you need precise, custom file layouts beyond what the higher level export functions provide.
Always check the exported file in a viewer or by re importing it to ensure it matches the intended format.

Views: 3

Comments

Please login to add a comment.

Don't have an account? Register now!