How to Save Plot in MATLAB: Simple Steps
To save a plot in MATLAB, use the
saveas function with the figure handle and filename, like saveas(gcf, 'filename.png'). Alternatively, use print for more control, e.g., print('filename','-dpng') saves the current figure as a PNG file.Syntax
The basic syntax to save a plot in MATLAB is:
saveas(fig, 'filename.ext'): Saves the figurefigto a file namedfilename.ext. The extension.extdetermines the file format (e.g.,.png,.jpg,.fig).print('filename','-dformat'): Saves the current figure to a file with the specified format, where-dformatis the device format like-dpng,-djpeg,-depsc.
matlab
saveas(gcf, 'myplot.png') print('myplot','-dpng')
Example
This example creates a simple plot and saves it as a PNG image file named example_plot.png.
matlab
x = 0:0.1:2*pi; y = sin(x); plot(x, y) title('Sine Wave') saveas(gcf, 'example_plot.png')
Output
A plot window showing a sine wave appears and the file 'example_plot.png' is saved in the current folder.
Common Pitfalls
- Not specifying the file extension in
saveascan cause MATLAB to save in the default format, which may not be what you want. - Using
saveaswith a filename that already exists will overwrite the file without warning. - Trying to save a plot before it is created or visible will cause errors.
- Using
printrequires specifying the correct device format; otherwise, the file may not save correctly.
matlab
plot(1:10) saveas(gcf, 'plotfile.fig') % Missing extension, saves as .fig by default print('plotfile','-dpng') % Correct way to save as PNG
Quick Reference
| Function | Usage | Description |
|---|---|---|
| saveas | saveas(fig, 'filename.ext') | Save figure to file with extension determining format |
| print('filename','-dformat') | Save current figure with specified device format | |
| gcf | gcf | Get current figure handle |
| close | close(fig) | Close figure window |
Key Takeaways
Use saveas with a figure handle and filename including extension to save plots easily.
print offers more control over file format and quality when saving plots.
Always specify the file extension to avoid unexpected file formats.
Save plots after they are created and visible to avoid errors.
Check the current folder for saved plot files or specify full path in filename.