How to save figures in a for loop?
6 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
Image Analyst
2014 年 12 月 23 日
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 件のコメント
Jakub Jurasz
2021 年 1 月 16 日
@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
2021 年 1 月 16 日
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
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Graphics Object Programming についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!