MATLAB Answers

How to save a figure through each run of a for loop?

950 views (last 30 days)
NH
NH on 23 Mar 2013
Edited: Sudheer Bhimireddy about 14 hours ago
Hello,
I am running a for loop:
for i=1:5
and in each loop, I am creating and saving a plot:
h=figure
plot(...)
saveas(h,'FIG','png');
end
This is problematic because 'FIG.png' is overwritten each time the for loop runs. How do I make it so that it saves 'FIG1.png','FIG2.png','FIG3.png', etc? In other words, how do I save FIG(i).png?
Thank you for your time.

  0 Comments

Sign in to comment.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 23 Mar 2013
Edited: Azzi Abdelmalek on 23 Mar 2013
for k=1:5
h=figure
plot(...)
saveas(h,sprintf('FIG%d.png',k)); % will create FIG1, FIG2,...
end

  5 Comments

Show 2 older comments
Kristian
Kristian on 22 Jan 2020
Hi, could I ask if there is a way to implement this using the print function? The saveas function doesn't allow me to change the resolution, so that is why I would want to use the print function. Or maybe there are other functions more suitable? Thank you!

Sign in to comment.

More Answers (3)

serena dsouza
serena dsouza on 2 Aug 2020 at 14:44
Hi, I am having same type of code but i want to save figures from two for loop.how can I do this.I have tried by following command but it is giving error.Thank you
for i=1:3
.
.
for k=1:5
h=figure
plot(...)
saveas(h,sprintf('FIG%d%d.png',ik));
end
end

  0 Comments

Sign in to comment.


Image Analyst
Image Analyst on 2 Aug 2020 at 15:37
If you have r2020a or later, try exportgraphics().

  2 Comments

serena dsouza
serena dsouza on 2 Aug 2020 at 16:38
I don't have it. I am working on r2016a. Is there any other solution??
Sudheer Bhimireddy
Sudheer Bhimireddy about 14 hours ago
You can try this,
for i=1:3
.
.
for k=1:5
h=figure;
plot(..);
fig_name = strcat('FIG_',num2str(i),'_',num2str(k));
print(h,fig_name,'-dpng','-r400');
end
end
This way you can print to your desired format and resolution.

Sign in to comment.