0
0
MatlabHow-ToBeginner ยท 3 min read

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 figure fig to a file named filename.ext. The extension .ext determines the file format (e.g., .png, .jpg, .fig).
  • print('filename','-dformat'): Saves the current figure to a file with the specified format, where -dformat is 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 saveas can cause MATLAB to save in the default format, which may not be what you want.
  • Using saveas with 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 print requires 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

FunctionUsageDescription
saveassaveas(fig, 'filename.ext')Save figure to file with extension determining format
printprint('filename','-dformat')Save current figure with specified device format
gcfgcfGet current figure handle
closeclose(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.