How do you save an array in MATLAB?

MATLAB provides several ways to save arrays and other data to files for later use. The most common methods include using the save and saveas functions. The save function allows saving multiple MATLAB variables, including arrays, to a single MATLAB data file with the .mat extension. The saveas function is used to export a MATLAB variable or figure to common file formats like .txt, .csv, .jpeg, etc. This article provides a detailed guide on the different ways to save arrays and other data in MATLAB along with specific examples.

Quick Answers

Here are quick answers to common questions on saving arrays in MATLAB:

How do I save an array to a .mat file in MATLAB?

Use the save command specifying the filename and variable name:

save(‘myarray.mat’,’A’)

How can I save multiple arrays in MATLAB?

List all the variables to save after the filename:


save(‘arrays.mat’,’A’,’B’,’C’)

What is the best way to export an array to Excel?

Use the xlswrite function to export the array to an Excel file:

xlswrite(‘myfile.xlsx’,A)

How do I save a MATLAB figure containing an array plot?

Use the saveas function to export the figure to an image or .fig file:

saveas(gcf,’arrayplot.jpg’)

Saving Arrays to .mat Files

The most common method for saving array data in MATLAB is to use the save function. This allows saving one or more arrays to a single .mat file that can be loaded back into MATLAB.

The basic syntax for the save function is:

save('filename.mat','array1','array2',...)

Where filename.mat is the name of the .mat file to create, and array1, array2, etc are the variable names of the arrays to save.

For example, to save a single array called A:

A = [1 2 3; 4 5 6]; 
save('myarray.mat','A');

This will save the array A to a file named myarray.mat in the current folder. The .mat extension indicates a MATLAB data file.

To save multiple arrays to the same file, list all the variable names:

A = [1 2 3; 4 5 6];
B = rand(5); 
C = zeros(10,1);
save('arrays.mat','A','B','C');

Now arrays A, B and C will be saved to arrays.mat. These can be loaded back into MATLAB using the load command:

load('arrays.mat')

This will load the variables A, B, C from the .mat file into the current workspace.

Appending to Existing .mat Files

By default, the save function overwrites any existing file with the same filename. To append new variables to an existing .mat file, use the -append option:

A = [1 2; 3 4]; 
save('arrays.mat','A'); 

B = [5 6; 7 8];
save('arrays.mat','B','-append');

Now arrays.mat will contain both A and B arrays.

Saving Array Metadata

MATLAB .mat files can also contain metadata such as variable names and sizes. To include metadata, use the -v7.3 option:

A = rand(5);
save('arrays.mat','A','-v7.3')

This stores the variable name ‘A’ and its size [5 5] in arrays.mat. The metadata allows identifying the contents of the file without loading it.

Exporting Arrays to CSV Files

Comma separated values (CSV) files are a simple text format for storing tabular data. MATLAB provides several functions to export arrays to CSV format.

Using csvwrite

The csvwrite function can be used to export a numeric array to a CSV file:

A = [1 2; 3 4; 5 6];
csvwrite('data.csv',A)

This will create a CSV file named data.csv containing:

1,2
3,4 
5,6

The numbers are separated by commas, with each row on a new line.

To include column and row headers, supply a cell array:

A = [1 2; 3 4; 5 6];
header = {'Col1','Col2'};
csvwrite('data.csv',[header;num2cell(A)]) 

This will add Col1, Col2 as header row.

Using dlmwrite

The dlmwrite function allows exporting arrays to CSV with a custom delimiter, such as tabs:

A = [1 2; 3 4];
dlmwrite('data.tsv',A,'delimiter','\t')

This creates a tab separated values (TSV) file data.tsv.

Controlling File Format

Additional options can control the format of the CSV file:

opts = csvwriteOptions;
opts.Delimiter = ',';
opts.EndOfLine = 'cr';
csvwrite('data.csv',A,opts)

This uses a comma delimiter, and Windows style CR end of line characters.

Exporting Arrays to Excel Files

MATLAB provides several ways to export array data to Excel workbooks.

Using xlswrite

The simplest approach is the xlswrite function:

A = [1 2; 3 4];
xlswrite('data.xlsx',A)

This will export array A to a new Excel file data.xlsx, starting at cell A1.

To append data to an existing sheet, specify the sheet and cell:

xlswrite('data.xlsx',B,'Sheet1','B3')

This will write array B to Sheet1 starting at cell B3, without overwriting A.

Controlling Excel Format

Additional parameters can control the Excel cell format:

xlswrite('data.xlsx',A,'','B2','NumberFormat','0.00')

This sets cell format to display 2 decimal places.

Using writematrix

The writematrix function provides more options for exporting to Excel:

A = [1 2; 3 4];
opts = spreadsheetImportOptions;
opts.VariableNames = {'x','y'};
writematrix(A,'data.xlsx','Sheet1','A1',opts)

This exports A with column names ‘x’ and ‘y’.

Exporting Multiple Arrays

To export multiple arrays to Excel, first concatenate them into a single matrix:

A = [1 2; 3 4]; 
B = [5 6; 7 8];
C = [A B];
writematrix(C,'data.xlsx')

This will write A and B side-by-side into columns A and B.

Saving MATLAB Figures containing Array Plots

When plotting arrays in MATLAB, the figures can be exported to standard image and vector formats using the saveas function.

For example, to export a figure containing an array image plot:

A = rand(10,10);
imshow(A)
saveas(gcf,'arrayimage.png')

This saves the current figure as a PNG image file arrayimage.png.

For array plots, some common formats include:

  • .jpg or .png – Compressed bitmap image
  • .svg – Vector image format
  • .fig – Saves the MATLAB figure for editing
  • .pdf – Vector format for high print quality

The format can be specified as a second argument to saveas:

saveas(gcf,'plot.jpg') % JPEG image 
saveas(gcf,'plot.svg') % SVG vector image

In addition to images, the underlying array data can also be exported using the techniques covered earlier.

Compressing .mat Files to Save Space

MATLAB .mat files containing large arrays can quickly grow to occupy a lot of disk space. To save space, .mat files can be compressed using the -v7.3 option:

save('arrays.mat','A','B','-v7.3')

The -v7.3 option enables compression using zlib, reducing file size by up to a factor of 10. The files remain fully compatible with MATLAB.

Existing .mat files can be compressed using the save command with the same filename:

load('arrays.mat')
save arrays.mat A B -v7.3

This loads arrays.mat, re-saves the variables with compression.

The compressed files take longer to read and write, so compression is best suited for archival of large datasets.

Saving Structures Containing Arrays

In MATLAB, arrays can be organized into structures to store related data together. These structures can also be saved to .mat files.

For example:

arrays.A = rand(5); 
arrays.B = rand(5,3);
save('arraystruct.mat','arrays')

This saves a structure called arrays containing A and B. The entire structure can be loaded back with:

load('arraystruct.mat')

Accessing the individual arrays:

C = arrays.A;
D = arrays.B;

Structures provide an organized way to store related arrays and other data together.

Saving Sparse Arrays

Sparse arrays contain mostly zero elements. MATLAB provides compressed storage for sparse arrays to reduce memory usage:

S = sparse(5,5);
S(1,1) = 1; 
save('sparse.mat','S')

Only the non-zero entries are stored. The .mat file will be much smaller compared to a full 5×5 array.

Sparse arrays are loaded the same way as regular arrays:

load('sparse.mat')

MATLAB automatically recognizes and expands the sparse array.

Saving Arrays to HDF5 Files

HDF5 is a flexible binary format designed for large, complex datasets. Arrays can be saved to HDF5 using the hdf5write function:

A = rand(1000,1000);
hdf5write('data.h5','/bigarray',A)

This saves array A to the group ‘/bigarray’ in data.h5. HDF5 supports complex nested directory structures.

To load arrays from HDF5:

[A, info] = hdf5read('data.h5','/bigarray');

HDF5 allows appending data to files as well as partial I/O for large datasets that don’t fit in memory. However, HDF5 files are not directly readable in MATLAB without hdf5read.

Saving to MATLAB MAT-files vs Other Formats

Format Description Benefits Limitations
.mat MATLAB native binary format
  • Full precision numeric data
  • Supports complex structures
  • Can compress well
  • MATLAB-only format
CSV/XLS Simple text/binary spreadsheet format
  • Portable across applications
  • Human-readable
  • Limited precision
  • No complex data structures
HDF5 Flexible binary scientific format
  • High capacity and performance
  • Supports complex data
  • More complex than .mat
  • Requires dedicated reader

MAT-files offer a compact, self-contained way to save MATLAB array data for exchange with other MATLAB users. For portability to other tools, CSV, Excel or HDF5 are better choices.

Conclusion

MATLAB provides a variety of options for saving arrays to files for later reuse. The key methods include:

  • save – Saves arrays to .mat files
  • csvwrite/dlmwrite – Writes arrays to CSV text files
  • xlswrite – Exports arrays to Excel spreadsheets
  • saveas – Saves figures as images
  • hdf5write – Writes arrays to HDF5 format

MAT-files provide an efficient way to save MATLAB data for exchange with other MATLAB users. For portability to other platforms, CSV, Excel or HDF5 are better choices. The optimal approach depends on the downstream usage of the data.

By understanding the options available for saving arrays in MATLAB, users can ensure that their data is stored in appropriate formats for future access and analysis.

Leave a Comment