Main Content

matfile

Access and change variables in MAT-file without loading file into memory

Description

Use a MAT-file object to access and change variables in a MAT-file without loading the file into memory. You can load or save parts of variables. Partial loading and saving of variables using a MAT-file object requires less memory than the load and save commands.

Creation

Description

matObj = matfile(filename) creates a matlab.io.MatFile object connected to the MAT-file specified by filename.

The MAT-file object allows you to access and change variables directly in a MAT-file, without having to load the variables into memory.

example

matObj = matfile(filename,"Writable",isWritable) enables or disables write access to the file. Specify isWritable as true or false.

example

Input Arguments

expand all

Name of MAT-file, specified as a string scalar or character vector.

If filename has no extension (that is, does not end with a period followed by text), matfile searches for a file whose name is filename with .mat appended to it. If the file does not exist, matfile creates a Version 7.3 MAT-file on the first assignment to a variable.

Depending on the location of your MAT-file, filename can be in one of these forms.

Location

Form

Current folder or folder on the MATLAB® path

Specify the name of the file in filename.

Example: "myFile.mat"

File in a folder

If the file is not in the current folder or in a folder on the MATLAB path, then specify the full or relative path in filename.

Example: "C:\myFolder\myFile.mat"

Example: "dataDir\myFile.mat"

Remote locations

If the file is stored at a remote location, then specify filename as a uniform resource locator (URL) of this form:

schemeName://pathToFile/fileName.mat

Based on your remote location, schemeName can be one of the values in this table.

Remote LocationschemeName
Amazon S3™s3
Windows Azure® Blob Storagewasb, wasbs

For more information on setting up MATLAB to access your online storage service, see Work with Remote Data.

Example: "s3://myBucket/myPath/myFile.mat"

Enable write access, specified as true or false. The default value is true for new files, false for existing files.

  • true — Enable write access to the MAT-file from the MAT-file object. If the file is read-only, change the system permissions by using the fileattrib function.

  • false — Disable write access to the MAT-file from the MAT-file object.

Properties

expand all

Access MAT-File Object Properties

Access MAT-file object properties using the syntax ObjectName.Properties.PropertyName, where PropertyName is the name of a property. For example, you can access the source file path of the MAT-file connected to the MAT-file object mObj using the syntax mObj.Properties.Source.

File path, returned as character vector containing the fully qualified path to the MAT-file.

Write access status of the MAT-file object, returned as either true or false.

  • true — MAT-file object has write access to the MAT-file.

  • false — MAT-file object has read-only access to the MAT-file.

Object Functions

size

Get array dimensions of variable in MAT-file

allDims = size(matObj,variable) returns the size of each dimension of the specified variable in the file corresponding to matObj. The output allDims is a 1-by-m vector, where m = ndims(variable).

[dim1,...,dimN] = size(matObj,variable) returns the sizes of each dimension in separate output variables dim1,...,dimN.

selectedDim = size(matObj,variable,dim) returns the size of the specified dimension.

Note: Do not call size with the syntax size(matObj.variable). This syntax loads the entire contents of the variable into memory. For very large variables, this load operation results in Out of Memory errors.

who

Get list of variables in MAT-file

varlist = who(matObj) lists alphabetically all variables in the MAT-file associated with matObj. Optionally, returns the list in cell array varlist.

varlist = who(matObj,variables) lists the specified variables.

whos

Get list of variables in MAT-file, with sizes and types

details = whos(matObj) returns information about all variables in the MAT-file associated with matObj.

details = whos(matObj,VarName1,...,VarNameN) returns information about the specified variables.

Examples

collapse all

Create a MAT-file object for your file. The matfile function constructs a matlab.io.MatFile object that corresponds to a MAT-File.

matObj = matfile('myFile.mat')

Enable write access to the MAT-file, myFile.mat, when you create the object.

m = matfile('myFile.mat','Writable',true);

Alternatively, you can enable write access after you create the MAT-file object by setting the Writable property.

m.Properties.Writable = true;

Open the sample MAT-file topography.mat. Read the variable topo from the file using the MAT-file object. MATLAB® loads the entire variable, topo, into the workspace.

m = matfile('topography.mat');
topo = m.topo;

Create a MAT-file containing an array and then add another array to the file using the MAT-file object.

Create a MAT file by generating a 20-by-20 array, x, and saving it to myFile.mat.

x = magic(20);
save('myFile.mat','x');

Create a MAT-file object connected to the existing MAT-file. Enable write access by setting Writable to true.

m = matfile('myFile.mat','Writable',true);

Generate another 15-by-15 array, y. Save y to the MAT-file using the MAT-file object. Specify the variable in the MAT-file using dot notation similar to accessing fields of structure arrays. MATLAB® adds a variable named y to the file.

y = magic(15);
m.y = y;

Display all variables stored in the MAT-file, myFile.mat.

whos('-file','myFile.mat')
  Name       Size            Bytes  Class     Attributes

  x         20x20             3200  double              
  y         15x15             1800  double              

Access specific parts of a variable in a MAT-file using the MAT-file object. For example, you can save data to a subset of a variable in a MAT-file or read a subset of a variable into the MATLAB® workspace.

Save data to a subset of a variable y in the file myFile2.mat using the MAT-file object. First, create the MAT-file object m.

m = matfile('myFile2.mat');

Next, create and save an array to part of the variable y. Specify the variable in the MAT-file using dot notation similar to accessing fields of structure arrays. MATLAB® inserts the 20-by-20 array into the elements of y specified by the indices (81:100,81:100).

m.y(81:100,81:100) = magic(20);

Read a subset of array y into a new workspace variable, z. MATLAB® reads the 10-by-10 subarray specified by the indices (85:94,85:94) from the MAT-file into workspace variable z.

z = m.y(85:94,85:94);

Determine the size of a variable, and then calculate the average of each column.

Open the example MAT-file, stocks.mat.

filename = 'stocks.mat';
m = matfile(filename);

Determine the size of the variable, stocks, in stocks.mat.

[nrows,ncols] = size(m,'stocks');

Compute the average of each column of the variable stocks.

avgs = zeros(1,ncols);
for i = 1:ncols
    avgs(i) = mean(m.stocks(:,i));
end

Change the size of a variable in a MAT-file.

Create a variable and save it to a MAT-file.

x = magic(20);
save myFile.mat x
whos -file myFile.mat
  Name       Size            Bytes  Class     Attributes

  x         20x20             3200  double              

Open the MAT-file and resize the variable.

m = matfile("myFile.mat",Writable=true);
m.x = magic(30);
whos -file myFile.mat
  Name       Size            Bytes  Class     Attributes

  x         30x30             7200  double              

Resize the variable again, this time making it smaller than it originally was.

m.x = magic(10);
whos -file myFile.mat
  Name       Size            Bytes  Class     Attributes

  x         10x10              800  double              

Limitations

  • When accessing parts of variables in MAT-files by indexing:

    • Linear indexing is not supported. You must specify indices for all dimensions.

    • Assigning complex values to indexed portions of a real array is not supported.

  • For sparse arrays in a MAT-file, the MAT-file object:

    • Supports reading a subset of a sparse array by indexing.

    • Does not support writing (assigning values) to a subset of a sparse array by indexing.

  • The MAT-file object does not support indexing into:

    • Variables of tables

    • Cells of cell arrays

    • String arrays

    • datetime arrays

    • duration arrays

    • Fields of structure arrays

    • User-defined classes

  • The MAT-file object does not support evaluating function handles using the m output. For example, if your MAT-file contains function handle myfunc, the syntax m.myfunc() attempts to index into the function handle, and does not invoke the function.

  • When saving a handle object, MATLAB saves a copy of the object, not a copy of the handle. Therefore, modifying the object via its handle in the workspace from which the object was saved does not modify the saved handle object.

Tips

  • Efficient partial loading and saving requires Version 7.3 MAT-files. To create a Version 7.3 MAT-file, call the save function with the '-v7.3' option. For example, to convert an existing MAT-file named durer.mat to Version 7.3, call:

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

  • Using the end keyword as part of an index causes MATLAB to load the entire variable into memory. For very large variables, this load operation results in Out of Memory errors. Rather than using end, determine the extent of a variable with the size method:

    sizeMyVar = size(matObj,'myVar')

Version History

Introduced in R2011b

expand all