Saving data to a MAT file lets you keep your work safe and load it later. It helps you reuse variables without running the whole program again.
0
0
MAT file save and load in MATLAB
Introduction
You want to save your workspace variables after a long calculation.
You need to share data with a friend or colleague who uses MATLAB.
You want to pause your work and continue later without losing data.
You want to load example data for testing your program.
You want to save results from a simulation to analyze later.
Syntax
MATLAB
save('filename.mat', 'var1', 'var2', ...) load('filename.mat')
The save command stores variables into a file with .mat extension.
The load command reads variables back into the workspace.
Examples
This saves variables
a and b into mydata.mat.MATLAB
a = 5; b = [1, 2, 3]; save('mydata.mat', 'a', 'b')
This clears variables and then loads them back from the file.
MATLAB
clear a b
load('mydata.mat')This saves all workspace variables into
allvars.mat.MATLAB
save('allvars.mat')This loads the file into a structure
data and accesses variable a.MATLAB
data = load('mydata.mat');
a = data.a;Sample Program
This program saves variables x and y to a file, clears them from memory, then loads them back and displays their values.
MATLAB
x = 10; y = [4, 5, 6]; save('example.mat', 'x', 'y') clear x y load('example.mat') disp(x) disp(y)
OutputSuccess
Important Notes
If you save without specifying variables, MATLAB saves all workspace variables.
Loading a MAT file restores variables with their original names.
You can also load into a structure to avoid overwriting existing variables.
Summary
Use save to store variables in a MAT file.
Use load to bring variables back into your workspace.
This helps keep your data safe and reuse it anytime.