Save figures from for loop into a subfolder of the current folder.
19 views (last 30 days)
Show older comments
I will use math notation instead of saying arrays etc. In what follows and . I want to plot each column of X against y on separate figures and save these figures as png files to a subfolder in my current folder called "Figures". I want each figure to be saved with the name 'ploti ' for each . When I run the code I dont want the figures to appear just to directly save into the file for me to view later.
This is my current script for example :
M=10;
N=5;
X=ones(N,M);
y=ones(N);
for i=1:M
fig=figure
plot(X(:,i),y,'Color','blue')
grid on
xlabel('x')
ylabel('y')
name=num2str(i);
saveas(fig,append('plot',name),'png')
end
But I get erros I think it is coming from my use of saveas but I spent ages trying to work out how to do it and the documentation on saveas was not very usefull. Moreover, the figures always open when I run the code (which I dont want). Can anyone show me how they would do it ?
2 Comments
Answers (1)
Dave B
on 9 Nov 2021
- To make the figures not appear, I'd set their Visible property to 'off'
- I'd also recommend exportgraphics on releases since 2020a.
- Your code executes fine, but it's plotting bunch of ones vs. ones, and plot defaults to no marker, so there's nothing visible in the plot. If you're getting an error, of course it's helpful if you tell us what it is...
for i = 1:3
f = figure('Visible','off');
plot(rand(1, 100))
exportgraphics(f,"foo" + i + ".png")
close(f)
end
3 Comments
Dave B
on 9 Nov 2021
I wouldn't expect an error with modifyColorsForPrint, if you continue to see that error - can you attach a .fig file and specify a release? I'm happy to debug a bit.
For working with a subfolder, it's good to use fullfile althout you can construct the path yourself (I actually think the more robust solution is to provide the full path to the export location).
fp = 'C:\foo\subf'; % on windows
%fp = '.\subf'; % relative path
fn = fullfile(fp, "foo" + i + ".png")
exportgraphics(f, fn)
See Also
Categories
Find more on Printing and Saving 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!