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

조회 수: 20 (최근 30일)
daniel adams
daniel adams 2021년 11월 9일
댓글: Dave B 2021년 11월 9일
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
daniel adams
daniel adams 2021년 11월 9일
It keeps pausing and saying "In workspace belonging to modifyColorsForPrint (line 70)"

댓글을 달려면 로그인하십시오.

답변 (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