How to save figures on the program general folder?
1 view (last 30 days)
Show older comments
Asier Rodriguez
on 24 Jan 2022
Commented: Asier Rodriguez
on 25 Jan 2022
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!
0 Comments
Accepted Answer
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.
end
% 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);
More Answers (1)
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')
mkdir(fd);
end
print(gcf,'-dpng','-r200',fullfile(fd, 'im'))
3 Comments
Image Analyst
on 25 Jan 2022
Similar except that this code hard coded in your folder (which youi were wanting to avoid since it's meant to run on other people's computers) while mine uses the current folder where the source code is, which will of course be different from one person to another. And I'm also using the newer isfolder() rather than the older exist().
The -'dpng' tells it to make the file a PNG image file. If "aux_Year" is a string with the extension PNG already specified, then it is not needed. If the aux_year does not have a .png in it, then the .png extension gets assed upon saving to disk.
The -r200 puts meta data for 200 dots per inch into the file so if your printing or display program pays attention to that, it will apply it and make the image appear as a certain size on paper or on the display. You can probably omit that option if you're not going to print your images to paper.
Both of those options are discussed in the documentation for print.
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!