How to Save Multiple Figures in Loop?

19 Ansichten (letzte 30 Tage)
ercan duzgun
ercan duzgun am 1 Okt. 2022
Kommentiert: ercan duzgun am 1 Okt. 2022
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.

Akzeptierte Antwort

Star Strider
Star Strider am 1 Okt. 2022
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 Kommentare
ercan duzgun
ercan duzgun am 1 Okt. 2022
Thank you very much @Star Strider
Star Strider
Star Strider am 1 Okt. 2022
As always, my pleasure!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 1 Okt. 2022
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.

Tags

Produkte


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by