How to Use save in MATLAB: Syntax and Examples
In MATLAB, use the
save command to store workspace variables to a file. You can save all variables or specify which ones to save by name, and choose the file format like .mat or ASCII text.Syntax
The basic syntax of save in MATLAB is:
save filename: Saves all workspace variables tofilename.mat.save filename var1 var2: Saves only specified variablesvar1andvar2.save filename -ascii: Saves variables in ASCII text format.save(filename, 'var1', 'var2'): Alternative function syntax to save specific variables.
matlab
save filename save filename var1 var2 save filename -ascii save(filename, 'var1', 'var2')
Example
This example shows how to save all variables and how to save selected variables to a file.
matlab
a = 10; b = rand(3); c = 'hello'; save('myData.mat'); % saves all variables clear a b c load('myData.mat') % loads all variables back save('selectedData.mat', 'a', 'c') % saves only a and c clear a c load('selectedData.mat') % loads only a and c
Output
a = 10
b = [3x3 double matrix]
c = 'hello'
After loading selectedData.mat:
a = 10
c = 'hello'
Common Pitfalls
Common mistakes when using save include:
- Forgetting to specify variable names when you want to save only some variables, which saves everything by default.
- Using
save filenamewithout quotes can cause errors if the filename has spaces or special characters. - Saving variables in ASCII format with
-asciionly works for numeric data, not strings or complex types.
matlab
% Wrong: saves all variables unintentionally save myFile % Right: save only needed variables save('myFile.mat', 'var1', 'var2')
Quick Reference
| Command | Description |
|---|---|
| save filename | Save all workspace variables to filename.mat |
| save filename var1 var2 | Save only var1 and var2 to filename.mat |
| save filename -ascii | Save variables in ASCII text format (numeric only) |
| save(filename, 'var1', 'var2') | Function syntax to save specific variables |
| load filename | Load variables from filename.mat back into workspace |
Key Takeaways
Use
save filename to save all workspace variables to a .mat file.Specify variable names to save only selected variables and reduce file size.
Use quotes around filenames to avoid errors with spaces or special characters.
The
-ascii option saves numeric data as text but cannot save strings.Always check saved files by loading them back with
load.