How to Save Multiple Figures in Loop?

19 visualizaciones (últimos 30 días)
ercan duzgun
ercan duzgun el 1 de Oct. de 2022
Comentada: ercan duzgun el 1 de Oct. de 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.

Respuesta aceptada

Star Strider
Star Strider el 1 de Oct. de 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 comentarios
ercan duzgun
ercan duzgun el 1 de Oct. de 2022
Thank you very much @Star Strider
Star Strider
Star Strider el 1 de Oct. de 2022
As always, my pleasure!

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 1 de Oct. de 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.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by