How to save a figure in MATLAB from the command line?

Is there a command in MATLAB which allows saving a figure in FIG or JPEG or both formats automatically?


Use saveas:

% ...

This way, the figure is plotted, and automatically saved to '.jpg' and '.fig'. You don't need to wait for the plot to appear and click 'save as' in the menu. Way to go if you need to plot/save a lot of figures.

If you really do not want to let the plot appear (it has to be loaded anyway, can't avoid that, else there is also nothing to save), you can hide it:


When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:

hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');

This will do exactly as manually saving the figure.


I don't think you can save it without it appearing, but just for saving in multiple formats use the print command. See the answer posted here: Save an imagesc output in Matlab

If you want to save it as .fig file, hgsave is the function in Matlab R2012a. In later versions, savefig may also work.

imwrite(A,filename) writes image data A to the file specified by filename, inferring the file format from the extension

These days (May 2017), MATLAB still suffer from a robust method to export figures, especially in GNU/Linux systems when exporting figures in batch mode. The best option is to use the extension export_fig

Just download the source code from Github and use it:

plot(cos(linspace(0, 7, 1000)));
set(gcf, 'Position', [100 100 150 150]);
export_fig test2.png

try plot(var); saveFigure('title'); it will save as a jpeg automatically

Need Your Help

remove specific html tags using php

php html

Since I dont want to use stip_tags function of php instead of I want to replace <script> and </script> to empty string so that output should be alert(1).

c# Regex matches too generous

c# regex

I need to confirm the format of a customer number, which needs to be the format of #####-## (# being a 0-9 digit and the dash being a literal dash).