Kahibaro
Discord Login Register

Saving and Loading Data Files

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

matlab
save

The file is saved in the current folder. If you want to specify a file name, write it as a string:

matlab
save('mySession.mat')

or

matlab
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:

matlab
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:

matlab
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:

matlab
save('data/results.mat')

If the folder name contains spaces, use full paths or ensure you use quotes:

matlab
save('my data/results.mat', 'a', 'b')

You can also provide an absolute path if you prefer, such as

matlab
save('C:\Users\YourName\Documents\MATLAB\session1.mat')

on Windows, or

matlab
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:

matlab
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:

matlab
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:

matlab
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:

matlab
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.

matlab
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:

matlab
load('mySession.mat')

If the file is in the current folder, you can omit the extension and parentheses:

matlab
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:

matlab
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:

matlab
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:

matlab
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:

matlab
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:

matlab
load('config.mat', 'settings')

Second, load into a structure so that nothing in your workspace is changed accidentally:

matlab
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:

matlab
x = 0:0.1:10;
y = sin(x);
result = [x.' y.'];

You then decide to save everything related to this computation:

matlab
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:

matlab
clear
load('sineData.mat')

Now x, y, and result are back in your workspace exactly as they were. You can continue, for example:

matlab
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:

matlab
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:

matlab
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:

matlab
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: 3

Comments

Please login to add a comment.

Don't have an account? Register now!