3.3. Saving and Loading Data Files
Table of Contents
Overview
When you work in MATLAB, your variables live only in memory. Once you close MATLAB or clear the workspace, those variables disappear. To keep your work, you must save it to disk. Later, you can load it back and continue exactly where you left off. This chapter focuses on how to save variables to files and how to load them again using basic commands and simple options.
Saving Variables with `save`
The core command for writing variables from the workspace to a file is save. At its simplest, you can save everything that is currently in the workspace to a file called matlab.mat by typing
saveThe file is saved in the current folder. If you want to specify a file name, write it as a string:
save('mySession.mat')or
save mySession.mat
In both forms, MATLAB stores all current workspace variables into the MAT file mySession.mat. Existing files with the same name in the current folder will be overwritten without a warning, so be careful when choosing file names.
You are not limited to saving everything. You can save only specific variables by listing their names after the file name. For example:
a = 10;
b = rand(3);
c = 'hello';
save('numbers.mat', 'a', 'b')
This creates numbers.mat containing the variables a and b but not c. The variable names in the save command must be written as character vectors or strings and must already exist in the workspace. If you try to save a variable that does not exist, MATLAB displays an error.
If you omit the file name and just list variable names, MATLAB uses the default name matlab.mat in the current folder:
save a b
Now matlab.mat contains only the variables a and b, replacing any previous file with that name.
Choosing File Names and Locations
By default, save writes to the current folder. You see this folder in the Current Folder panel and in the path shown at the top of the MATLAB desktop. To save to a different folder, include a relative or absolute path in the file name.
For example, to save into a subfolder called data inside the current folder:
save('data/results.mat')If the folder name contains spaces, use full paths or ensure you use quotes:
save('my data/results.mat', 'a', 'b')You can also provide an absolute path if you prefer, such as
save('C:\Users\YourName\Documents\MATLAB\session1.mat')on Windows, or
save('/home/yourname/Documents/MATLAB/session1.mat')on Linux or macOS. Make sure that the folder exists, otherwise MATLAB will not be able to create the file.
The file extension .mat is the conventional choice for MAT files and is recognized by MATLAB and many related tools. MATLAB does not require you to type the extension, but using it keeps your files organized and clear.
Choosing What to Save
There are several patterns you might use depending on how you work with MATLAB.
If you want a full snapshot of the workspace, for example at the end of a long session, use:
save('fullWorkspace.mat')This captures everything, including temporary variables that you might no longer need. Reloading later will return all of them.
If you only need a few key results, for example processed data and a configuration, it is more controlled to specify them:
save('results.mat', 'processedData', 'config')This approach keeps your MAT files smaller and better organized, and also helps you remember what the file is meant to contain.
Sometimes you might compute results in stages and want to add new variables to an existing MAT file. If you use save with a file name and variables, MATLAB will update or add variables in that file. For example:
save('results.mat', 'summary') % first run
save('results.mat', 'details', '-append') % add a new variable
In the second call, the option -append tells MATLAB to keep the existing contents and just add or update the variables you specify. Without -append, MATLAB would overwrite the entire file.
Basic Options for `save`
While save works without any options, you may sometimes use a few simple flags. One very common option is -append, which adds variables to an existing MAT file instead of replacing it.
For example:
save('run1.mat', 'x', 'y')
z = x + y;
save('run1.mat', 'z', '-append')
After this sequence, run1.mat contains x, y, and z.
In addition, when you store plain text data instead of MATLAB’s binary MAT format, you can use -ascii to write a simpler numeric file. Only use this for numeric arrays and be aware that you may lose some precision and data types when saving this way.
A = rand(5);
save('matrix.txt', 'A', '-ascii')
This saves matrix A as a text file with numeric values separated by spaces. It does not store variable names or types. MATLAB can read these values back but they will not be associated with their original variable names automatically.
Within this course, the main format you will work with is the default MAT file format, without special format options. The key idea is that MAT files preserve MATLAB data types and structures exactly, which makes saving and loading very simple.
Loading Variables with `load`
To bring saved variables back into your workspace, use load. The simplest case is to load everything from a MAT file:
load('mySession.mat')If the file is in the current folder, you can omit the extension and parentheses:
load mySession
After running this command, all variables stored in mySession.mat appear in the workspace, usually with the same names and values they had when you saved them. MATLAB displays no message by default, but you can see the variables in the Workspace browser or by using whos.
You can also load only selected variables from a MAT file. This is helpful when a file contains many variables but you only need one or two. You list the variable names after the file name:
load('results.mat', 'processedData')
In this example, MATLAB reads only the variable processedData from results.mat, and leaves the rest on disk. If the variable is not found inside the file, MATLAB gives an error.
Sometimes you want more control over how loaded data is introduced into the workspace. By default, load creates variables with their names directly in the current workspace. If a variable with the same name already exists, it will be overwritten silently. To avoid unexpected overwrites, you can load into a structure instead, which is described later in this chapter.
Loading from Different Locations and Text Files
Just like save, the load command works relative to the current folder. If your MAT file lives elsewhere, you provide the path:
load('data/run1.mat')If the file is not found, MATLAB reports an error. You can always change your current folder or check its location using the desktop interface if you are unsure where you are working.
If you saved numeric data using the -ascii option, you can read it back with load as well:
B = load('matrix.txt')
In this case, MATLAB reads the file contents as a numeric array and returns it as the output of load. This form is different from loading MAT files, where variables are created directly in the workspace. When you assign the output of load to a variable, you treat load more like a function that returns data.
For MAT files, you can also load into an output variable. For example, if results.mat contains variables a and b, you can write:
S = load('results.mat')
Now S is a structure whose fields are S.a and S.b. This is useful if you want to inspect or manage the loaded variables without mixing them directly into your current workspace. It also lets you access the data later without overwriting any existing variables with the same names.
Avoiding Variable Name Conflicts
When you load variables directly into the workspace without capturing the output, name conflicts can occur. If a variable with the same name already exists, MATLAB replaces it silently, which can be confusing if you are not expecting it.
To minimize this risk, there are a few practical approaches.
First, only load the variables you actually need using the list form:
load('config.mat', 'settings')Second, load into a structure so that nothing in your workspace is changed accidentally:
data = load('config.mat');
Now you can use data.settings instead of a bare settings variable. This also makes it clear where the data came from.
Finally, be mindful of your file naming and saving patterns. If you treat MAT files as self-contained data bundles with clear names, and you choose distinct variable names for different roles, you will reduce the chance of conflicts.
Example Workflow: Save, Clear, Load, Continue
A typical session might look like this. You start by computing some intermediate variables and final results:
x = 0:0.1:10;
y = sin(x);
result = [x.' y.'];You then decide to save everything related to this computation:
save('sineData.mat', 'x', 'y', 'result')Later, perhaps after closing MATLAB or working on another task, you return and want to continue analysis. To simulate a fresh start, you might clear the workspace and then load the saved data:
clear
load('sineData.mat')
Now x, y, and result are back in your workspace exactly as they were. You can continue, for example:
plot(x, y)This simple pattern of save, clear, and load allows you to break your work into stages and resume without repeating computations.
Inspecting MAT Files
Sometimes you may want to know what variables a MAT file contains before loading it. You can use whos together with -file for that purpose:
whos('-file', 'results.mat')
MATLAB then lists variables stored in results.mat along with their sizes and types. Based on that information, you can decide which variables to load:
load('results.mat', 'summary', 'parameters')This avoids unnecessary clutter in your workspace and also helps you understand how a MAT file is organized.
Saving from Scripts and Loading in Other Sessions
You can use save and load inside scripts just as you use them at the command line. For example, a script might load input data at the beginning, perform computations, and then save the output:
load('rawData.mat', 'measurements')
processed = mean(measurements, 2);
save('processedData.mat', 'processed')
The next day, you can run a different script that starts from processedData.mat instead of rawData.mat, which saves time and keeps your workflow modular.
MAT files can be moved, copied, and shared like any other file. Another MATLAB user can place them in their current folder and use load to access the contents. As long as they know what variables are inside, they can integrate the data into their own scripts and functions.
Important things to remember:
Use save('file.mat') to keep your workspace variables, and load('file.mat') to bring them back.
Specify variable names in save and load if you only want some of the variables.
Using save without -append replaces any existing file with the same name.
Loading directly with load file.mat can overwrite variables silently if names match.
Load into a structure with S = load('file.mat') to avoid workspace conflicts and to inspect contents safely.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!