Storing the Plots in a Folder While Running the Matlab Program?

In my MATLAB program I have to run a for loop for 500 times and each time the loop runs it plots a graph, so If I run the program there will be 500 (.fig files) and that may hang my system.

So is there any way that I can save the output which are produced after each loop automatically in some folder?.

If there is some procedure, a reference to that procedure will be very much helpful!.

1 Answer

You can use the saveas method.

For example, to save a simple bar plot as a png file:

x = [2 4 7 2 4 5 2 5 1 4];
bar(x);
saveas(gcf,'Barchart.png')

or as an eps file:

saveas(gcf,'Barchart','epsc')

Make sure you use a filename that depends on something that varies in each loop iteration to not overwrite the file. You can use sprintf to create the new file name, e.g. to save an eps file:

for k = 1:500
    filename = sprintf('%s_%d','Barchart',k);
    % Create the plot
    saveas(gcf,filename,'epsc')
end

See the link to the documentation for more configurations and filetypes.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest