How can i save instantaneously all plots of a script?

9 views (last 30 days)
Hello,
I have a script in which several graphs are created. I would like these to be automatically saved in predefined folders that I decide. For now I'm writing below each figure:
fig = gcf;
ax = fig.CurrentAxes;
ax.FontSize = 17;
fig.PaperUnits = 'centimeter';
fig.PaperPosition = [0 0 29.7 21];
saveas (fig, [pwd, '/ MATLAB / Immagini_tesi_Matlab / OBIDOS / RELIABILITY / NA_SCENARIO / Relmodel.png']);
I wondered if there is a way to extend this automatic procedure to all the figures with a single command.
Thanks in advance

Answers (1)

Jan
Jan on 7 Mar 2018
There is no single command, but you can write a function to do this:
function SaveAllFigures
Folder = fullfile(pwd, '/MATLAB/Immagini_tesi_Matlab/OBIDOS/RELIABILITY/NA_SCENARIO/');
AllFigH = allchild(groot);
for iFig = 1:numel(AllFigH)
fig = AllFigH(iFig);
ax = fig.CurrentAxes;
ax.FontSize = 17;
fig.PaperUnits = 'centimeter';
fig.PaperPosition = [0 0 29.7 21];
FileName = [fig.Title, '.png'];
saveas(fig, fullfile(Folder, FileName));
end
end
Maybe the file name should be numbered instead:
FileName = sprintf('Image%03d.png', iFig);
  • fullfile is safer than the concatenation of the char vectors.
  • I have removed the spaces around the file separators in the folder name.
  • Relying on the current folder by pwd is dangerous: it can be changed by callbacks of GUIs or timers unexpectedly. Better provide the base folder as input argument to your function.
  5 Comments
Jan
Jan on 8 Mar 2018
Edited: Jan on 8 Mar 2018
@Gianluca Borgna: Again, please do not post comments in the section for answers, because this will look confusing if more answers are given and voting reorders them.
Maybe you mean:
if choice == 1
FolderName = 'NA_SCENARIO';
elseif choice == 2
FolderName = 'PREV_SCENARIO'
elseif ...
end
SaveAllFigures(FolderName);
And a slightly modified function:
function SaveAllFigures(FolderName)
Folder = fullfile(pwd, '/MATLAB/Immagini_tesi_Matlab/OBIDOS/RELIABILITY/', FolderName);
...

Sign in to comment.

Categories

Find more on Printing and Saving in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!