You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
how can I change the code to save every figure my code does?
7 views (last 30 days)
Show older comments
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
Adam Danz
on 30 Dec 2021
Edited: Adam Danz
on 30 Dec 2021
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
flashpode
on 30 Dec 2021
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
flashpode
on 30 Dec 2021
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
flashpode
on 30 Dec 2021
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
Adam Danz
on 30 Dec 2021
> 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.
Adam Danz
on 30 Dec 2021
Edited: Adam Danz
on 30 Dec 2021
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.
flashpode
on 30 Dec 2021
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
Adam Danz
on 30 Dec 2021
> 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.
flashpode
on 30 Dec 2021
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};
flashpode
on 30 Dec 2021
If I dont run the code you send me my code runs well but I do not save the figures
Adam Danz
on 30 Dec 2021
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
Adam Danz
on 30 Dec 2021
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.
flashpode
on 30 Dec 2021
I changed this line from your code
filename = {dinfo.name};
and it works but It does save the images with different names now
Image Analyst
on 30 Dec 2021
- What kind of files does it want to open?
- 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?
Adam Danz
on 30 Dec 2021
> 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...
flashpode
on 30 Dec 2021
@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?
Adam Danz
on 30 Dec 2021
> 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.
- Implement my exact answer in your file. The only thing you should change is the folder path.
- Run the code.
- 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.
- Attach the updated file that contains my exact solution without changing anything else.
flashpode
on 30 Dec 2021
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
Voss
on 30 Dec 2021
@Adam Danz @Image Analyst Some necessary context (and missing function definition) can be found here: https://www.mathworks.com/matlabcentral/answers/1619310-how-can-i-do-a-code-that-compares-each-document-one-by-one-and-get-all-the-information-i-want#answer_864885
@vicente Noguer renaming a function is not the same as writing a function.
Adam Danz
on 30 Dec 2021
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
Voss
on 31 Dec 2021
@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).
More Answers (1)
Image Analyst
on 30 Dec 2021
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
flashpode
on 30 Dec 2021
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
Image Analyst
on 30 Dec 2021
Edited: Image Analyst
on 30 Dec 2021
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
flashpode
on 30 Dec 2021
Warning: UI components will not be included in the output.
I have this warning coming up every time
Image Analyst
on 30 Dec 2021
Not sure why. I use it all the time on the whole figure and get buttons, listboxes, and all kinds of other UIControls.
Adam Danz
on 30 Dec 2021
@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.
flashpode
on 30 Dec 2021
@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
See Also
Categories
Find more on Printing and Saving in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)