Save figures from for loop into a subfolder of the current folder.

15 次查看(过去 30 天)
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 ?

回答(1 个)

Dave B
Dave B 2021-11-9
  • 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 个评论
daniel adams
daniel adams 2021-11-9
Hi Dave, imagine I have a subfolder in my current working folder called FiguresFolder. How would you modify your code to save the figures to that folder?
Dave B
Dave B 2021-11-9
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)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Printing and Saving 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by