How to save figures in a for loop?

15 views (last 30 days)
I've created a for loop for 5 subjects. The first times the loop runs, I get a plot for subject one. I want to save this figure under the name 'plot_subject_1'. The next time the loop runs, I want to save the figure under the name 'plot_subject_2'. How do I do this?

Accepted Answer

Image Analyst
Image Analyst on 23 Dec 2014
This is well covered by the first set of well-commented code in the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F I'm sure you'll have no trouble using sprintf() and fullfile() to create your filenames after you see the FAQ. Let us know if you can't get it to work.
Inside the loop, use export_fig() to save the figures or axes as PNG images (or other formats). http://blogs.mathworks.com/pick/2010/05/28/creating-and-exporting-publication-quality-graphics/
  6 Comments
Jakub Jurasz
Jakub Jurasz on 16 Jan 2021
@Image Analyst It has been long time since you have posted this.
I am following your answers and I find them super helpful.
Any ideas how to speed up saving the figures in a loop when a lot of figures is about to be saved? PNG are relatively small but after saving 400 of them Matlab is already using over 1GB of ram.
for i=1:8760;
figure()
% code for making the figure - quite long, a mix of surfplot + countour
saveas(gcf,sprintf('Fig_%d.png',i));
clf
end
I am thinking about doing it in batches but I guess there must be a way to do it faster.
Any help would be much appreicated!
Image Analyst
Image Analyst on 16 Jan 2021
Try moving figure outside the for loop. There is probably no need to create a new figure each iteration. Also make sure hold is not on when you display the image and you might do a "cla reset" before each call to imshow()
hfig = figure;
for k = 1 : 8760
fileName = whatever...
cla reset;
% code for making the figure - quite long, a mix of surfplot + countour
exportgraphics(gcf, sprintf('Fig_%d.png', k)); % Or gca instead of gcf.
% exportgraphics() available in R2020a or later.
clf
end

Sign in to comment.

More Answers (1)

nikhil baraiya
nikhil baraiya on 29 Jan 2019
Its Working Fine Thanks

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!