Skip to Main Content Skip to Search
Accelerating the pace of engineering and science

Technical Solutions

Can I save a plot or figure to an M-File so that it can be loaded back into MATLAB?


Date Last Modified: 03 Apr 2009
Solution ID:   1-15KWU
Product:   MATLAB
Reported in Release:  
Fixed in Release:  
Platform:   All Platforms
Operating System:   All OS
 

Subject:

Can I save a plot or figure to an M-File so that it can be loaded back into MATLAB?

Problem Description:

Is it possible to save a plot or figure to an M-File so that it can be reloaded into MATLAB to allow further work to be done on the plot?

Solution:

The recommended method of saving a plot to update in the future is to create an M-file that contains all of the commands that were used to create this plot. This is the only foolproof method for saving a figure that is to be brought back into MATLAB. M-files can also be passed between platforms since they are ascii-text files.

However, a "print" command device driver option was added to MATLAB version 4.2 that allows you to save and reload a figure. The command

print -dmfile [filename]

creates two files, filename.m and filename.mat. The M-file contains the necessary object creation and set commands to reproduce the figure. The generated MAT-file also contains the figure data. Handle values are not maintained. Also, when printing figures with multiple axes, especially on the PC, the resulting M-file may not be identical with the original.

If you are using a version of MATLAB earlier than 4.2c, there is a command in MATLAB called HARDCOPY. HARDCOPY is used by PRINT to create a postscript file. An undocumented feature of HARDCOPY is that it can also produce an M-file based on the current Figure. For example:


plot(1:10)
hardcopy(gcf,'filename','-dm')
clf
filename


This will generate the plot(1:10) again.

Also, this is useful if you want to suppress the graphical output during an M-file; however, you still want the generate plots of the data so that you can display them later. Here is an example:


% Create an M-file and add the following:
rootname = 'tstplt'; % Root file name
for i = 1:10 % Create 10 plots/files
plot(sin(0:pi/10:i*pi));
hardcopy(gcf,[rootname,int2str(1)],'-dm')
drawnow discard
clf
end


This will create 10 files named tstplt1.m through tstplt10.m. To display the plots again, simply run the appropriate file.

  Provide feedback to help us improve this solution!
Contact support