how can I change the code to save every figure my code does?

hi I've got the followed code and I want to get a diferend name for each figure my code does. How can i do it?
AllFigH = allchild(groot);
for iFig = 1:numel(AllFigH)
fig = AllFigH(iFig);
Folder = ('C:\Users\vicen\Desktop\TFG Vicenç\Imagenes\Imagenes Geoscatter\DIA 1')
FileName = ['%03d', '.png'];
saveas(fig, fullfile(Folder, FileName));
end
thank you in advance!!

 Accepted Answer

It looks like you wanted to do,
AllFigH = allchild(groot);
for iFig = 1:numel(AllFigH)
fig = AllFigH(iFig);
Folder = ('C:\Users\vicen\Desktop\TFG Vicenç\Imagenes\Imagenes Geoscatter\DIA 1')
FileName = sprintf('%03d.png', iFig); % <-----
saveas(fig, fullfile(Folder, FileName));
end
I recommend using
AllFigH = findall(groot, 'type','figure')
rather than
AllFigH = allchild(groot);
Update: avoid overwriting filenames
This version searches the folder for png files with a naming structure of ###.png and then determines the maximum number in the file names. The new file numbers will continue with the next value.
Folder = 'C:\Users\vicen\Desktop\TFG Vicenç\Imagenes\Imagenes Geoscatter\DIA 1';
% Get all png filenames in folder.
filedata = dir(fullfile(Folder,'*.png'));
% Determine the max number in the file names ###.png
if isempty(filedata)
lastFileNumber = 0;
else
filenames = {filedata.name};
filenumStr = regexp(filenames,'^(\d+).png$','tokens','once');
filenums = str2double([filenumStr{:}]);
lastFileNumber = max(filenums);
end
% Save figures with new numbers in the file names
AllFigH = findall(groot, 'type','figure');
for iFig = 1:numel(AllFigH)
fig = AllFigH(iFig);
FileName = sprintf('%03d.png', lastFileNumber + iFig); %
saveas(fig, fullfile(Folder, FileName));
end

31 Comments

it saves me ust one figure not all of them
Are you getting an error message?
I just tested it and it works fine with regular figures.
Note that this will not work with uifigures in which case you would receive an error message.
it is saveing me the figures but with the same name so it does not work I want to get a different number for each figure
Perhaps your implementation is incorrect. Or maybe you are overwriting old files.
The screen recording below shows the production of 4 figures and then those figures appear in the folder.
I get this erro using the following code line
AllFigH = allchild(groot);
this error:
Error using saveas (line 83)
Invalid figure handle.
Error in prova (line 223)
saveas(fig,fullfile(Folder,FileName));
using the other line of code:
AllFigH = findall(groot, 'type','figure')
I get just one image not all I use this code:
AllFigH = findall(groot, 'type','figure')
for iFig = 1:numel(AllFigH)
fig = AllFigH(iFig);
Folder = ('C:\Users\vicen\Desktop\TFG Vicenç\Imagenes\Imagenes Geoscatter\DIA 1');
FileName = sprintf('%03d.png',iFig); % <-----
saveas(fig,fullfile(Folder,FileName));
end
Don't use allchild(groot). Objects other than figures can be children of the graphics root.
How are you generating the figures?
Perhaps you could attach one of the figures that you think are not being saved.
I use geoscatter but I seen that maybe is better to create a figure list no?
figure(1)
geoscatter(lat1, lon1)
hold on
geoscatter(lat2,lon2,'filled')
legend('AIS1','AIS2')
hold off
it is just saved the last figure of the loop
> maybe is better to create a figure list no?
AllFigH = findall(groot, 'type','figure')
This line creates a figure list.
Check the value of AllFigH.
As my GIF image shows, there shouldn't be a problem. Please attach several of the figures you're trying to save.
the value of AllFigH is 1x1 figure. I can't attached figures I do not have
Ok, you're running in circles here.
You stated, "it is just saved the last figure of the loop" and then you claim that "the value of AllFigH is 1x1 figure". So Matlab is only detecting ONE figure which is the last figure in the loop.
So now I'm trying to figure out if Matlab is not detecting some of your figures or if you're confusing the term "figure" to mean something else.
Please attach several of the figures you're trying to save.
well as the code is running the figures are showed in the screen and saved, but as the code continues the followed figure is saved with the same name as the one before and the one that was saved is losted I do not know if I explained now but the only way it worked to me was using the function exportgraphics but I do not know how to change the path
> but as the code continues the followed figure is saved with the same name as the one before and the one that was saved is losted
Ahhhh... Thank you. This clearly describes the problem.
I'll update my answer in a few minutes.
I am getting this problem, that comes from the beggining of the code
Index exceeds the number of array elements (1).
Error in prova (line 8)
thisfile = filenames{K};
If I dont run the code you send me my code runs well but I do not save the figures
That line (thisfile = filenames{K}) is not part of my solution.
Test my solution in isolation by producing several figures as shown below and then run my the code from my answer in isolation.
figure
figure
figure
yeah both codes for separated work but when you join them do not work
it runs till the second figure then I get the error
If you share the full copy-pasted error message along with the code that is producing the error, I have a chance at helping out.
I changed this line from your code
filename = {dinfo.name};
and it works but It does save the images with different names now
here is the full code. Do not know why now does not work your code
  1. What kind of files does it want to open?
  2. What is importfileAIS()? I don't have that function. Is it something you wrote, or is it a function in a toolbox I don't have?
> it runs till the second figure then I get the error
If you share the full copy-pasted error message I can help.
> I changed this line from your code...
But your change introduced an error.
Look at my version....
and compare it to your version...
@Adam Danz yeah both versions are different because I modified it because it did not work. Writting dinfo.name it worked the code but not saving the figures. With filedata.name it was stopping in the second figure with the problem I told you before :
Index exceeds the number of array elements (1).
Error in prova (line 8)
thisfile = filenames{K};
so that I why I changed it.
@Image Analyst yes It is a function I made some months ago. And what do you mean in the first question?
> I modified it because it did not work
if you want me to help you fix that, I need to know the entire copy-pasted error message. If there was not an error, I need to have a clear description of what didn't work.
Your correction introduces problems. It's a bad correction. In your call to dinfo = dir(__), you are listing all files and folders in the directory. In my call to filedata = dir(__), I am only listing png files since those are the only files we care about in that section of the code.
Here's what you need to do so that I can help you.
  1. Implement my exact answer in your file. The only thing you should change is the folder path.
  2. Run the code.
  3. If there is an error, show me the entire error message. if there is not an error message but you don't think it worked correctly, describe what is wrong. But do not change anything else.
  4. Attach the updated file that contains my exact solution without changing anything else.
Okay so, I runned the whole code and I got an error when it was meant to begin comparing the third file( only got saved the two first figures). The error is the following:
Index exceeds the number of array elements (1).
Error in prova (line 8)
thisfile = filenames{q};
the matlab code is attached
I see now. The error occurs because my variable name filenames overwrites your variable with the same name.
To fix that, change my variable name. This change was made in 2 lines below. Make these changes to these two lines only and then test it. If there is an error, please provide that information before you make any further changes.
% Get all png filenames in folder.
filedata = dir(fullfile(Folder,'*.png'));
% Determine the max number in the file names ###.png
if isempty(filedata)
lastFileNumber = 0;
else
pngfilenames = {filedata.name}; % <----- CHANGED VARIABLE NAME
filenumStr = regexp(pngfilenames,'^(\d+).png$','tokens','once'); % <----- CHANGED VARIABLE NAME
filenums = str2double([filenumStr{:}]);
lastFileNumber = max(filenums);
end
now It worked perfectly. Thank you!!
@Benjamin I attached my function for you to see that is not yours is it another one different created some moths ago. I wasn't using it because I thought it was not necessary and when you gave yours it gave me problems so I changed to mine
@vicente Noguer OK, sorry for the misunderstanding. For future reference, it's a good idea to include any functions your code is dependent on so that others can run it (and to avoid any ambiguity about what they might be).

Sign in to comment.

More Answers (1)

I would call exportgraphics() everytime you're done creating a plot. I'd create it immediately, not sometime later after all plots have been made.

9 Comments

it is a loop that when finishes comparing creates a plot and begins comparing the followed documents till the folder its finished so I do not know
Yeah, so no problem
for k = 1 : 3
figure(k);
plot(rand(1,5), '.-'); % Plot something.
fileName = fullfile(pwd, sprintf('Plot #%d.png', k));
exportgraphics(gca, fileName);
end
and the name its changed every time the loop is done?
Warning: UI components will not be included in the output.
I have this warning coming up every time
Not sure why. I use it all the time on the whole figure and get buttons, listboxes, and all kinds of other UIControls.
but what are UI components?
should I worry about it? and how can I save them in a folder I want?
@vicente Noguer, I have a feeling you're not communicating effectively and I appologize if I'm wrong about that assumption.
If you're using ui components you must be generating a uifigure. I specifially asked how you are generating the figures and you ignored my question. I also asked to share error messages and the solution in my answer should produce an error if you're using uifigures since saveas() does not work with uifigures. But you did not share that error message.
It's very difficult to help you if you're not communicating effectively.
@Adam Danz I said some messages before I generate the figures with geoscatter and I upload the code(I do not know if you meant that) and I have never listened about uicomponents so thats why I was surprised. I got this warning but I could save the images the only problem I have is to save them in the folder I want. With saveas() I did not get any error of uicomponents

Sign in to comment.

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Asked:

on 30 Dec 2021

Commented:

on 31 Dec 2021

Community Treasure Hunt

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

Start Hunting!