How to Save Multiple Figures in Loop?

11 次查看(过去 30 天)
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.
.

更多回答(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