How to Save Multiple Figures in Loop?

조회 수: 18 (최근 30일)
ercan duzgun
ercan duzgun 2022년 10월 1일
댓글: ercan duzgun 2022년 10월 1일
Could you help me to save multiple plot/figure files using loop number?
My code is:
clear all;clc;
k=1:1:10
k = 1×10
1 2 3 4 5 6 7 8 9 10
for i=1:15
x=i*sin(i*pi/4)*k;
y=i*2*cos(i*pi/2)*k;
plot(x,y)
sprintf(gcf, '-dtiff', 'File%d_6.tiff',i);
end
Error using sprintf
Invalid format.

채택된 답변

Star Strider
Star Strider 2022년 10월 1일
Perhaps this instead —
saveas(gcf, sprintf('File%02d_6.tiff',i), '-dtiff');
Specifing the numeric field as '%02d' creates a two-digit numeric field and pads single digits with a leading zero. That should make it easier to sort and recover the files.
See the documentation on saveas for more information.
.
  댓글 수: 2
ercan duzgun
ercan duzgun 2022년 10월 1일
Thank you very much @Star Strider
Star Strider
Star Strider 2022년 10월 1일
As always, my pleasure!

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

추가 답변 (1개)

Image Analyst
Image Analyst 2022년 10월 1일
You can use the newer exportgraphics in the loop:
clear all;
clc;
k = 1 : 10
for i = 1 : 15
x = i * sin(i*pi/4) * k;
y = i * 2 * cos(i*pi/2) * k;
plot(x, y, 'b-', 'LineWidth', 2);
grid on;
drawnow;
% Save current graph to its own file.
fullFileName = fullfile(pwd, sprintf('Plot %2.2d.png', i));
exportgraphics(gcf, fullFileName); % gcf to save the whole figure window, or gca to save only the graph.
end
fprintf('Done!!\n')
Be aware that your code just plots a series of lines, not sine or cosine curves since sin(i*pi/4) is just a single scalar, not a vector of 10 or 15 values, like perhaps you were expecting.
Use "hold on" after the plot if you want to show all the plot curves on the same graph.
You can also use subplot if you want all 10 plots on one figure window.

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by