save figure to image file in matlab

To save a figure to an image file in MATLAB, you can use the saveas function. This function takes the figure handle and the file name as input arguments, and the file format is inferred from the file extension of the specified file name. Here's an example code snippet that saves a figure to a PNG file:

main.m
% create a sample plot
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y);

% save the figure to a PNG file
filename = 'myplot.png';
fig = gcf;  % get current figure handle
saveas(fig, filename);
196 chars
10 lines

In this example, gcf returns the handle of the current figure, which is then passed to saveas along with the file name 'myplot.png'. You can replace 'myplot.png' with any file name and extension you want (e.g. 'myplot.jpg', 'myplot.tif', etc.) to save the figure in a different format.

related categories

gistlibby LogSnag