Skip to Main Content Skip to Search
Product Documentation

Importing MAT-Files

View the Contents of a MAT-File

MAT-files are binary MATLAB format files that store workspace variables.

To see the variables in a MAT-file before loading the file into your workspace, click the file name in the Current Folder browser. Information about the variables appears in the Details Panel.

Alternatively, use the command whos -file filename. This function returns the name, dimensions, size, and class of all variables in the specified MAT-file.

For example, view the contents of the demo file durer.mat:

whos -file durer.mat

MATLAB returns:

 Name           Size               Bytes  Class     Attributes

  X            648x509            2638656  double              
  caption        2x28                 112  char                
  map          128x3                 3072  double              

The byte counts represent the number of bytes that the data occupies when loaded into the MATLAB workspace. Compressed data uses fewer bytes in a file than in the workspace. In Version 7 or higher MAT-files, MATLAB compresses data. For more information, see MAT-File Versions.

Ways to Load Data from a MAT-File

Load All Variables

Import all variables from a MAT-file using one of the following options:

To load variables into a structure array, specify an output variable for the load function:

durerStruct = load('durer.mat')

Load Selected Variables

To interactively select and load MAT-file variables, use any of the following options:

Alternatively, use the load or matfile function.

The load function imports the entire contents of one or more variables. For example, load variables X and map from durer.mat:

load('durer.mat','X','map')

With the load function, you can load variables whose names match a pattern. For example, load all variables that start with A from a hypothetical file named fakefile.mat,

load('fakefile.mat','A*')

or load variables that start with Mon, Tue, or Wed using a regular expression,

load('fakefile.mat','-regexp','^Mon|^Tue|^Wed')

The matfile function allows you import part of a variable, which requires less memory than loading an entire variable. For example, load the first 50 rows from variable topo in topography.mat into a variable called partOfTopo:

topography = matfile('topography.mat');
partOfTopo = topography.topo(1:50,:);

For more information, see:

Load Part of a Variable from a MAT-File

This example shows how to load part of a variable from an existing MAT-file. To run the code in this example, create a Version 7.3 MAT-file with two variables.

A = rand(5);
B = magic(10);
save example.mat A B -v7.3;
clear A B

Load the first column of B from example.mat into variable firstColB.

example = matfile('example.mat')
firstColB = example.B(:,1);

The matfile function creates a matlab.io.MatFile object that corresponds to a MAT-file:

  matlab.io.MatFile

  Properties:
      Properties.Source: C:\Documents\MATLAB\example.mat
    Properties.Writable: false                                                
                      A: [5x5   double]                                       
                      B: [10x10 double]

When you index into objects associated with Version 7.3 MAT-files, MATLAB loads only the part of the variable that you specify.

The primary advantage of matfile over the load function is that you can process parts of very large data sets that are otherwise too large to fit in memory. When working with these large variables, the best practice is to read and write as much data into memory as possible at a time. Otherwise, repeated file access negatively impacts the performance of your code.

For example, suppose a variable in your file contains many rows and columns, and loading a single row requires most of the available memory. To calculate the mean of the entire data set, calculate the mean of each row, and then find the overall mean.

example = matfile('example.mat');
[nrows, ncols] = size(example,'B');

avgs = zeros(1, nrows);
for idx = 1:nrows
    avgs(idx) = mean(example.B(idx,:));
end
overallAvg = mean(avgs);

By default, matfile only allows loading from existing MAT-files. To enable saving, call matfile with the Writable parameter,

example = matfile('example.mat','Writable',true);

or construct the object and set Properties.Writable in separate steps:

example = matfile('example.mat');
example.Properties.Writable = true;

Avoid Inadvertently Loading Entire Variables

When you do not know the size of a large variable in a MAT-file, and want to load parts of that variable at a time, do not use the end keyword. Rather, call the size method for matlab.io.MatFile objects. For example, this code

[nrows,ncols] = size(example,'B');
lastColB = example.B(:,ncols);

requires less memory than

lastColB = example.B(:,end);

which temporarily loads the entire contents of B. For very large variables, loading takes a long time or generates Out of Memory errors.

Similarly, any time you refer to a variable with syntax of the form mfObj.varName, such as example.B, MATLAB temporarily loads the entire variable into memory. Therefore, make sure to call the size method for matlab.io.MatFile objects with syntax such as

[nrows,ncols] = size(example,'B');

rather than passing the entire contents of example.B to the size function,

[nrows,ncols] = size(example.B);

The difference in syntax is subtle, but significant.

Partial Loading Requires Version 7.3 MAT-Files

Any load or save operation that uses a matlab.io.MatFile object associated with a Version 7 or earlier MAT-file temporarily loads the entire variable into memory.

The matfile function creates files in Version 7.3 format. For example, this code

newfile = matfile('newfile.mat');

creates a MAT-file that supports partial loading and saving.

However, by default, the save function creates Version 7 MAT-files. Convert existing MAT-files to Version 7.3 by calling the save function with the -v7.3 option, such as

load('durer.mat');
save('mycopy_durer.mat','-v7.3');

To change your preferences to save new files in Version 7.3 format, select File > Preferences > General > MAT-Files.

Troubleshooting: Loading Variables within a Function

If you define a function that loads data from a MAT-file, and find that MATLAB does not return the expected results, check whether any variables in the MAT-file share the same name as a MATLAB function. Common variable names that conflict with function names include i, j, mode, char, size, and path.

For example, consider a MAT-file with variables height, width, and length. If you load these variables using a function such as findVolume,

function vol = findVolume(myfile)
  load(myfile);
  vol = height * width * length;

MATLAB interprets the reference to length as a call to the MATLAB length function, and returns an error:

Error using length
Not enough input arguments.

To avoid confusion, when defining your function, choose one (or more) of the following approaches:

To determine whether a particular name is associated with a MATLAB function, use the exist function.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS