Prefoninsane
Prefoninsane

Reputation: 103

Save images in a loop with variable file names?

I have a loop as such:

for n = 1:6
figure
plot()
saveas(gcf,'figure', 'jpeg')
end

This however just keeps saving the figures over each other since they all have the same name. What I need is to make it so the name is 'figure_n' where n is the iteration of the loop.

Upvotes: 2

Views: 3071

Answers (2)

lakshmen
lakshmen

Reputation: 29064

for i=1:6
    % construct the filename for this loop - this would be `str1` in your example
    file_name = sprintf('picture_%i.jpeg', i);
    % or:
    file_name = strcat('picture_', num2str(i), '.jpeg');
    % call the function with this filename:
    saveas(gcf,'file_name','jpeg') 
end

Hope this helps.

Upvotes: 2

P0W
P0W

Reputation: 47784

Use num2str

saveas(gcf, ['figure_' num2str(n) ], 'jpeg') ;

Upvotes: 1

Related Questions