이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
how can I change the code to save every figure my code does?
조회 수: 11 (최근 30일)
이전 댓글 표시
flashpode
2021년 12월 30일
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!!
채택된 답변
Adam Danz
2021년 12월 30일
편집: Adam Danz
2021년 12월 30일
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
flashpode
2021년 12월 30일
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
2021년 12월 30일
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
2021년 12월 30일
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
2021년 12월 30일
> 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
2021년 12월 30일
편집: Adam Danz
2021년 12월 30일
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
2021년 12월 30일
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
2021년 12월 30일
> 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
2021년 12월 30일
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
2021년 12월 30일
If I dont run the code you send me my code runs well but I do not save the figures
Adam Danz
2021년 12월 30일
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
2021년 12월 30일
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
2021년 12월 30일
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
2021년 12월 30일
- 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
2021년 12월 30일
> 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
2021년 12월 30일
@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
2021년 12월 30일
> 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
2021년 12월 30일
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
2021년 12월 30일
@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
2021년 12월 30일
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
2021년 12월 31일
@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).
추가 답변 (1개)
Image Analyst
2021년 12월 30일
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
flashpode
2021년 12월 30일
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
2021년 12월 30일
편집: Image Analyst
2021년 12월 30일
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
2021년 12월 30일
Warning: UI components will not be included in the output.
I have this warning coming up every time
Image Analyst
2021년 12월 30일
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
2021년 12월 30일
@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
2021년 12월 30일
@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
참고 항목
카테고리
Help Center 및 File Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- 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)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)