2

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.

Prefoninsane
  • 103
  • 1
  • 11

2 Answers2

2
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.

lakshmen
  • 28,346
  • 66
  • 178
  • 276
  • I like to use the '%02i' option in the `sprintf`, so the files are numbered 01,02,... and not 1,2,... This way if you have more then 10 files, they get sorted correctly when you sort the folder by file name. – Itamar Katz Jul 10 '14 at 18:56
1

Use num2str

saveas(gcf, ['figure_' num2str(n) ], 'jpeg') ;
P0W
  • 46,614
  • 9
  • 72
  • 119
  • simple and works! Side question, how would I change that line of code to save all the images to a folder on my desktop? – Prefoninsane Jul 10 '14 at 18:45
  • @user3145111 Something like `saveas(gcf, ['C:\path_to_folder_on_desktop\' 'figure_' num2str(n) ], 'jpeg') ;` – P0W Jul 10 '14 at 18:53