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

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

It keeps pausing and saying "In workspace belonging to modifyColorsForPrint (line 70)"

Sign in to comment.

Answers (1)

  • 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

Hi Dave thanks, I will try this. Of course In my actual file im not plotting a load of 1s I just wrote it like this for simplicity.
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?
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)

Sign in to comment.

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Asked:

on 9 Nov 2021

Commented:

on 9 Nov 2021

Community Treasure Hunt

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

Start Hunting!