MATLAB crashes when saving figures in a loop
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I haven't been able to find any other answers that address this specifically. I'm trying to write a script that generates a bunch of figures and saves them as images, and since there's thousands of images to generate, I'm doing it in a loop.
I've created a simplified script that still reproduces the problem I'm having:
for iteration = 1:1000
% Generate some data
x = 1:100;
y1 = randi(100, 1, 100);
y2 = y1 + 1;
% Plot the data
figure
hold on
plot(x, y1, '-r');
plot(x, y2, '-b');
% Save an image
filename = ['iteration' num2str(iteration)];
saveas(1, [filename '.png']);
% Close the figures
close all
end
The above code usually crashes with a Segmentation Violation somewhere around iteration 15 or so.
Any idea what would be causing this to crash? Is there a preferable way to do what I'm trying to do here?
3 Kommentare
KALYAN ACHARJYA
am 30 Jul. 2018
Bearbeitet: KALYAN ACHARJYA
am 30 Jul. 2018
Its perfectly works in my case. Have you try to save the image as jpg, this not a strong reason, maybe it works. You can try
- #Clear the workspace
- #Exit the Matlab and restart again
- #First Try 100, if it works then only go for 10000
There are only hit and trials options available to you.
Hope it helps
Antworten (1)
OCDER
am 30 Jul. 2018
I'm suspecting an issue with the graphics card. https://www.mathworks.com/matlabcentral/answers/103051-why-do-i-receive-a-segmentation-violation-related-to-opengl-when-i-display-surface-plots-in-matlab-7.
Try updating your graphics card driver.
Also try this for debugging purposes. If an error occurs, do you see "plotted ok" or "saved ok" as the final message?
for iteration = 1:10
x = 1:100;
y1 = randi(100, 1, 100);
y2 = y1 + 1;
FH = figure('visible', 'off'); %<=visible off. Tracking figure handle as FH.
hold on
plot(x, y1, '-r');
plot(x, y2, '-b');
disp('plotted ok'); %Debugging, no message = error in plotting
saveas(FH, sprintf('iteration%d.png', iteration)); %Using sprintf
disp('saved ok'); %Debugging, no message = error in saving
close all
end
Or try the "painters" renderer when saving. Replace the saveas with print.
print(FH, sprintf('iteration%d.png', iteration), '-dpng', '-r300', '-painters');
Siehe auch
Kategorien
Mehr zu Creating, Deleting, and Querying Graphics Objects finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!