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.
  1 件のコメント
ercan duzgun
ercan duzgun 2022 年 10 月 1 日
Dear @Image Analyst, thank you very much.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by