How to Save the Workspace Variables to a .MAT File in MATLAB

The function save saves workspace variables to a file.


save(filepath) saves all variables in the workspace to the .MAT file filepath. If filepath only indicates the filename, such as ‘myfile.mat’, MATLAB saves the file in the current directory.

If the file filepath exists, it is overwritten.
% Save all workspace variables to the file 'workspace.mat' in the current directory


Apply this procedure to make the workspace variables persistent between sessions, so you can use in the current session variables created in previous sessions:

  1. Add Code 1 to the ‘startup.m’ file
  2. Add Code 2 to the ‘finish.m’ file
% Code 1
userPathArray = strsplit(userpath,';');
filepath = fullfile(userPathArray{1},'workspace.mat');
if(exist(filepath,'file')) load(filepath); end        
% Code 2
userPathArray = strsplit(userpath,';');

Further reading

I recommend the following books to learn more on the MATLAB environment.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. The first chapter explains the windows of the MATLAB environment, among other introductory topics like operators, random numbers, and trigonometry.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The second chapter explains the windows of the MATLAB environment, how to name variables, and how to save a series of commands in an .M file, among other topics.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc save;

Source code

I hope you have learned how to save the workspace variables to a .MAT file in MATLAB. The source code developed in this tutorial is available at this page.


Your friends may need this knowledge to complete a task. Share this tutorial.