How to save figures on the program general folder?

1 view (last 30 days)
Hey there!
I have been trying to store generated figures on both .png and .fig format on the same folder where the original code is located but I would like to keep it as simple as possible. I want an Examples internal sub-folder to contain them. My first idea was using the whole route:
saveas(figures.(aux_year),['C:\Users\ .... .... ....\Examples\Balance_energetico_',aux_year],'png');
Nevertheless I discarded this idea since I want to program to be open source and adapt to every user's possible location. Is there a shorter or simpler way to do so?
Thanks in advance!

Accepted Answer

Image Analyst
Image Analyst on 25 Jan 2022
Use pwd to get the current folder where your source code is, and then use fullfile(), isfolder(), and exportgraphics():
% Define the output folder as a subfolder of the current folder.
outputFolder = fullfile(pwd, 'Examples');
if ~isfolder(outputFolder)
mkdir(outputFolder); % Create folder if it does not exist yet.
% Create the base filename, and then prepend the output folder:
baseFileName = sprintf('Balance_energetico_%4.4d.png', aux_year);
fullFileName = fullfile(outputFolder, baseFileName);
fprintf('Writing "%s".\n', fullFileName);
% Export the current figure (screenshot) to a file.
% You could also use gca if you want the current axes instead of the whole figure.
exportgraphics(gcf, fullFileName);
  1 Comment
Asier Rodriguez
Asier Rodriguez on 25 Jan 2022
Thank you very much for the help! In this way I will be saving space from this project onwards

Sign in to comment.

More Answers (1)

yanqi liu
yanqi liu on 25 Jan 2022
yes,sir,may be use exportfig or print comand,such as
fd = fullfile('C:\Users\ your\Examples\Balance_energetico_',aux_year);
if ~exist(fd, 'dir')
print(gcf,'-dpng','-r200',fullfile(fd, 'im'))
Asier Rodriguez
Asier Rodriguez on 25 Jan 2022
Thank you very much for the clarification. I will consider it for future codification processes

Sign in to comment.




Community Treasure Hunt

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

Start Hunting!