0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use load in MATLAB: Syntax and Examples

In MATLAB, use the load function to read variables from a .mat file into the workspace. You can load all variables or specify particular ones by name using load('filename.mat') or load('filename.mat', 'var1', 'var2').
๐Ÿ“

Syntax

The load function reads data from a MAT-file or ASCII file into the MATLAB workspace.

  • load('filename'): Loads all variables from the file named filename.mat.
  • load('filename', 'var1', 'var2'): Loads only the specified variables var1 and var2 from the file.
  • S = load('filename'): Loads variables into a structure S instead of the workspace.
matlab
load('data.mat')
load('data.mat', 'x', 'y')
S = load('data.mat')
๐Ÿ’ป

Example

This example shows how to save variables to a file and then load them back using load. It demonstrates loading all variables and loading specific variables into the workspace and a structure.

matlab
% Create variables
x = 10;
y = [1, 2, 3];
z = 'hello';

% Save variables to a MAT-file
save('example.mat', 'x', 'y', 'z')

% Load all variables from the file
load('example.mat')

% Display loaded variables
disp(x)
disp(y)
disp(z)

% Load only x and y into a structure
S = load('example.mat', 'x', 'y');
disp(S.x)
disp(S.y)
Output
10 1 2 3 hello 10 1 2 3
โš ๏ธ

Common Pitfalls

Common mistakes when using load include:

  • Forgetting the file extension .mat if the file is not in the current folder or path.
  • Loading variables without assigning to a structure can overwrite existing workspace variables silently.
  • Trying to load variables that do not exist in the file causes an error.
  • Using load on non-MAT files without specifying format can cause unexpected results.
matlab
% Wrong: overwrites workspace variables unexpectedly
load('example.mat')

% Right: load into a structure to avoid overwriting
S = load('example.mat');
x = S.x;
y = S.y;
๐Ÿ“Š

Quick Reference

Summary tips for using load in MATLAB:

  • Use load('file.mat') to load all variables.
  • Use load('file.mat', 'var1', 'var2') to load specific variables.
  • Assign output to a structure to avoid overwriting workspace variables.
  • Ensure the file is in the current folder or provide the full path.
โœ…

Key Takeaways

Use load('filename.mat') to load all variables from a MAT-file into the workspace.
Specify variable names in load to load only those variables and save memory.
Assign load output to a structure to prevent overwriting existing workspace variables.
Always check the file path and extension to avoid file not found errors.
Loading variables that do not exist in the file will cause an error.