Main Content

save

Save variables from workspace to file

Description

example

save(filename) saves all variables from the current workspace in a binary MATLAB® file (MAT-file) named filename. If filename exists, save overwrites the file.

example

save(filename,variables) saves only the variables or fields of a structure array specified by variables.

example

save(filename,variables,fmt) saves in the file format specified by fmt. The variables argument is optional. If you do not specify variables, the save function saves all variables in the workspace.

example

save(filename,variables,version) saves to the MAT-file version specified by version. The variables argument is optional.

example

save(filename,variables,version,"-nocompression") saves the variables to the MAT-file without compression. The "-nocompression" option supports only MAT-file Version 7 (default) and Version 7.3. Therefore, you must specify version as "-v7" or "-v7.3". The variables argument is optional.

example

save(filename,variables,"-append") adds new variables to an existing file. If a variable already exists in a MAT-file, then save overwrites it with the value in the workspace.

For ASCII files, "-append" adds data to the end of the file.

To append to a Version 6 MAT-file, you must also specify version as "-v6".

example

save(filename,variables,"-append","-nocompression") adds new variables to an existing file without compression. The existing file must be a MAT-file Version 7 (default) or 7.3.

example

save filename is the command form of the syntax. Command form requires fewer special characters. You do not need to type parentheses or enclose the input in single or double quotes. Separate inputs with spaces instead of commas. If any input includes spaces, enclose it in single quotes.

For example, to save a file named test.mat, these statements are equivalent:

save test.mat    % command form
save("test.mat") % function form

You can include any of the inputs described in previous syntaxes. For example, to save the variable X to a file named my file.mat:

save 'my file.mat' X    % command form, using single quotes
save("my file.mat","X") % function form, using double quotes

Do not use command form when any of the inputs, such as filename, are variables.

Examples

collapse all

Save all variables from the workspace in a binary MAT-file, test.mat. If filename is a variable, use function syntax.

filename = "test.mat";
save(filename)

Otherwise, you also can use command syntax.

save test.mat

Remove the variables from the workspace, and then retrieve the data with the load function.

clear
load("test.mat")

Create and save two variables, p and q, to a file named pqfile.mat.

p = rand(1,10);
q = ones(10);
save("pqfile.mat","p","q")

The save function saves the variables to the file pqfile.mat, in the current folder.

You also can use command syntax to save the variables p and q.

save pqfile.mat p q

Create two variables, save them to an ASCII file, and then view the contents of the file.

p = rand(1,3);
q = ones(3);
save("pqfile.txt","p","q","-ascii")
type("pqfile.txt")
   8.1472369e-01   9.0579194e-01   1.2698682e-01
   1.0000000e+00   1.0000000e+00   1.0000000e+00
   1.0000000e+00   1.0000000e+00   1.0000000e+00
   1.0000000e+00   1.0000000e+00   1.0000000e+00

Alternatively, use command syntax for the save operation.

save pqfile.txt p q -ascii

Create a structure that contains three fields.

s1.a = 12.7;
s1.b = {"abc",[4 5; 6 7]};
s1.c = "Hello!";

Save the fields of structure s1 as individual variables in a file named newstruct.mat.

save("newstruct.mat","-struct","s1")

Check the contents of the file using the whos function.

whos("-file","newstruct.mat")
  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double              
  b         1x2               390  cell                
  c          -                150  string              

Create two variables and save them to a Version 7.3 MAT-file named example.mat.

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

You also can use command syntax for the save operation.

save example.mat A B -v7.3

Create two variables and save them, without compression, to a Version 7.3 MAT-file named myFile.mat.

A = rand(5);
B = magic(10);
save("myFile.mat","A","B","-v7.3","-nocompression")

Alternatively, use the command syntax for the save operation.

save myFile.mat A B -v7.3 -nocompression

The "-nocompression" option facilitates a faster save.

Save two variables to a MAT-file. Then, append a third variable to the same file.

p = rand(1,10);
q = ones(10);
save("test.mat","p","q")

View the contents of the MAT-file.

whos("-file","test.mat")
  Name       Size            Bytes  Class     Attributes

  p          1x10               80  double              
  q         10x10              800  double              

Create a new variable, a, and append it to the MAT-file.

a = 50;
save("test.mat","a","-append")

View the contents of the MAT-file.

whos("-file","test.mat")
  Name       Size            Bytes  Class     Attributes

  a          1x1                 8  double              
  p          1x10               80  double              
  q         10x10              800  double              

The save function appends the variable a to test.mat without overwriting the previous variables p and q.

Note: To append to a Version 6 MAT-file, specify both "-v6" and "-append". For example, to append variable a to the Version 6 MAT-file test.mat, run:

save("test.mat","a","-v6","-append")

Save two variables to a MAT-file. Then append a third variable, without compression, to the same file.

Create two variables, A and B, and save them to a MAT-file Version 7.3. By default, the save function compresses variables before saving them to myFile.mat.

A = rand(5);
B = magic(10);
save("myFile.mat","A","B","-v7.3")

View the contents of the MAT-file.

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

  A          5x5               200  double              
  B         10x10              800  double              

Create a new variable, C, and append it, without compression, to myFile.mat.

C = 5;
save("myFile.mat","C","-append","-nocompression")

View the contents of the MAT-file.

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

  A          5x5               200  double              
  B         10x10              800  double              
  C          1x1                 8  double              

Create several variables and use command syntax to save them to a file called myMat.mat.

a = 1;
b = 2;
c = 7;
d = 4;
save myMat.mat a c

Modify the c variable.

c = 3;

Save only workspace variables that already exist in myMat.mat.

existingVars = whos("-file","myMat.mat");
save("myMat.mat",existingVars.name)

Input Arguments

collapse all

Name of file, specified as a string scalar or character vector. If you do not specify filename, the save function saves to a file named matlab.mat.

If filename has no extension (that is, does not end with a period followed by text), and the value of format is not specified, then the save function appends .mat to filename. If filename does not include a full path, the save function saves to the current folder. You must have permission to write to the file.

To save workspace variables to a MAT-file in a remote location, specify filename as a uniform resource locator (URL) of this form:

scheme_name://path_to_file/my_file.mat

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

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

The save function supports saving to remote locations only for Version 7.3 MAT-files.

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

When using the command form of save, you do not need to enclose the input in single or double quotes. However, if filename contains a space, you must enclose the argument in single quotes. For example, save 'filename withspace.mat'.

Example: "myFile.mat"

Example: "s3://bucketname/path_to_file/my_file.mat"

Names of variables to save, specified as one or more string scalars or character vectors. When using the command form of save, you do not need to enclose the input in single quotes.

variables can be in one of these forms.

Form of variables InputVariables to Save
var1,var2,...,varNSave the listed variables, specified as individual string scalars or character vectors. Use the "*" wildcard to match patterns. For example, save("filename.mat","A*") or save filename.mat A* saves all variables in the workspace whose names start with A.
"-regexp",expr1,expr2,...,exprNSave only the variables whose names match the regular expressions, specified as string scalars or character vectors. For example, save("filename.mat","-regexp","^Mon","^Tues") or save filename.mat -regexp ^Mon ^Tues saves only the variables in the workspace whose names begin with Mon or Tues.
"-struct",structName Save the fields of the scalar structure specified by structName as individual variables in the file. For example, save("filename.mat","-struct","S") saves the fields of the scalar structure S.
"-struct",structName,field1,field2,...,fieldNSave the specified fields of the specified scalar structure as individual variables in the file. For example, save("filename.mat","-struct","S","a","b") saves the fields S.a and S.b.
"-struct",structName,"-regexp",expr1,expr2,...,exprNSave only the fields whose names match the regular expressions, specified as string scalars or character vectors.

File format, specified as one of the values in this table.

Value of fmtFile Format
"-mat"

Binary MAT-file format

"-ascii"

Text format with 8 digits of precision

"-ascii","-tabs"

Tab-delimited text format with 8 digits of precision

"-ascii","-double"

Text format with 17 digits of precision

"-ascii","-double","-tabs"

Tab-delimited text format with 17 digits of precision

When using the command form of save, you do not need to enclose the input in single or double quotes. For example, save myFile.txt -ascii -tabs.

For MAT-files, data saved on one machine and loaded on another machine retains as much accuracy and range as the different machine floating-point formats allow.

Use one of the text formats to save MATLAB numeric values to text files. In this case:

  • Each variable must be a 2-D double array.

  • The output includes only the real component of complex numbers.

  • The save function writes data from each variable sequentially to the file. If you plan to use the load function to read the file, all variables must have the same number of columns. The load function creates a single variable from the file.

If you specify a text format and any variable is a character array, then the save function translates characters to their corresponding internal ASCII codes. For example, 'abc' appears in a text file as:

  9.7000000e+001  9.8000000e+001  9.9000000e+001

When saving to a remote location, save supports specifying fmt only as "-mat".

Data Types: string | char

MAT-file version, specified as one of the values in this table. When using the command form of save, you do not need to enclose the input in single or double quotes.

Value of versionLoads in MATLAB VersionsSupported FeaturesCompressionMaximum Size of Each Variable
"-v7.3"7.3 (R2006b) or later

Saving parts of variables, and all Version 7 features.

Yes (default)≥ 2 GB on 64-bit computers
"-v7"7.0 (R14) or later

Unicode® character encoding, which enables file sharing between systems that use different default character encoding schemes, and all Version 6 features. Version 7 also supports saving variables without compression using the "-nocompression" option.

Yes (default)231 bytes per variable
"-v6"5 (R8) or later

Saving N-D arrays, cell arrays, and structure arrays; variable names longer than 19 characters; and all Version 4 features.

No231 bytes per variable
"-v4"All

Saving 2-D double, character, and sparse arrays.

No100,000,000 elements per array, and 231 bytes per variable

If any data items require features that the specified version does not support, the save function does not save those items and issues a warning. You cannot specify a version later than your current version of MATLAB software.

Note

Version 7.3 MAT-files use an HDF5-based format that requires some overhead storage to describe the contents of the file. For cell arrays, structure arrays, or other containers that can store heterogeneous data types, Version 7.3 MAT-files are sometimes larger than Version 7 MAT-files.

Note

Version 6 and Version 4 MAT-files support only ASCII character encoding.

To view or set the default version for MAT-files, go to the Home tab and in the Environment section, select Preferences. Select MATLAB > General > MAT-Files and then choose a MAT-file save format option.

Data Types: string | char

Limitations

  • Attempting to save data from two separate MATLAB sessions to the same file at the same time may lead to corruption of the file.

Tips

  • For more flexibility in creating ASCII files, use fprintf.

  • Saving graphics objects with the save function can result in a large file because the file contains all the information required to regenerate the object.

  • Saving figures with the save function is not recommended. Use the savefig function instead. Using save to save a figure in R2014b or later makes a MAT-file inaccessible in earlier versions of MATLAB. If you use save to save a figure, then the function displays a warning message. Delete any figures before using save. Keep in mind that the figures might not be directly in your workspace, but might, for example, be stored in a structure or in the workspace of a callback function.

  • The filename argument can be any name that is valid on the current platform. However, to ensure the load function can access the file on any platform, do not use any of these characters in filename: \ (backslash), / (forward slash), : (colon), * (asterisk), ? (question mark), " (double quotation mark), < (less than sign), > (greater than sign), | (pipe), ' (apostrophe), or ; (semicolon).

Extended Capabilities

Version History

Introduced before R2006a

expand all