Changing file path in a loop and save figures

7 ビュー (過去 30 日間)
Ancalagon8 2022 年 10 月 15 日
コメント済み: Jan 2022 年 11 月 10 日
I want to run a code where inside every folder i have a data file and save in each folder a .fig. Can anyone help me?
  17 件のコメント
Jan 2022 年 11 月 10 日
@Ancalagon8: Please do not delete essential parts of the question. Afterwards the time spent for writing the answers is wasted. If all users do this, this forum would be useless. Therefore your "cleaning" is counter-productive and will reduce the interest to help you in the future.


回答 (2 件)

Simon Chan
Simon Chan 2022 年 10 月 15 日
Try this to indicate the entire path:
  5 件のコメント
Stephen23 2022 年 10 月 17 日
編集済み: Stephen23 2022 年 10 月 17 日
"I tried..."
Why did you stick DIR inside the loop like that? The entire point of DIR is to get a list of any files that match the specified name, it will also automatically detect all folders. The code I gave you replaces all of your (complex, non-working) code by using DIR more effectively.
"There is a typo in Stephens suggestion:"
No, I specifically did not want a recursive search. One star will match any subfolder, matching the OPs description.


Stephen23 2022 年 10 月 17 日
編集済み: Stephen23 2022 年 10 月 18 日
As I wrote earlier, you need to get DIR to more of the work for you. It is simpler and much more efficient when you let DIR do as much as possible matching names and folders. I will demonstrate this here on the forum, but you should be able to adapt this to your own files.
First lets create some fake data files in subfolders:
for k = 'A':'D' % DO NOT COPY
mkdir(k) % DO NOT COPY
writematrix(rand(3,3),fullfile(k,'test.txt')) % DO NOT COPY
clearvars % DO NOT COPY
Now lets use DIR to get a structure array of those files in all subfolders:
P = '.'; % absolute/relative path to where the subfolders are.
S = dir(fullfile(P,'*','test.txt')); % one line is much simpler than your code.
Note how a single asterisk is sufficient to match subfolders (without recursion). We can check what DIR found:
{} % view check the filenames % DO NOT COPY
ans = 1×4 cell array
{'test.txt'} {'test.txt'} {'test.txt'} {'test.txt'}
{S.folder} % view the corresponding subfolder names % DO NOT COPY
ans = 1×4 cell array
{'/users/mss.system.T3k1jK/A'} {'/users/mss.system.T3k1jK/B'} {'/users/mss.system.T3k1jK/C'} {'/users/mss.system.T3k1jK/D'}
And then all you need to do is loop over those files:
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
... do whatever with this filename
  8 件のコメント
Rik 2022 年 10 月 24 日
I don't see what confidential information might be encoded in the path. You published it yourself under a creative commons license when you posted the mat file. I have therefore removed your flag.



Find more on Entering Commands 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!

Translated by