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

18 ビュー (過去 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 件のコメント
Yongjian Feng
Yongjian Feng 2021 年 11 月 9 日
what error did you get?
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 Center および File ExchangePrinting and Saving についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by