Opening files with for loop, switches to parent directory

1 view (last 30 days)
Hi everyone,
I am trying to loop through a number of files in a folder. To pick the names of the files I use the following code:
d = dir('*.mat');
for i=1:size(d,1);
files{i} = [d(i).name];
end
for j=1:35
file=char(files(j));
load (file)
The first loop works fine giving me a vector with all the files in the folder. However, as soon as I run the second loop the variable files contains not the 35 files I need , but has suddenly 140 file names of the parent directory. Of course this gives me an error as the files it tries to load is not in my current directory. So I was wondering if anyone knows why this sudden switch happens and how I could stop it from happening. Thanks in advance!
-Theresa

Accepted Answer

dpb
dpb on 13 Jun 2018
I'm thinking the code shown doesn't have such a symptom; the content of the variable file will be that of files as there is no refresh of the dir() struct.
However, it's inefficient code as well as having "magic numbers" of a counted loop instead of using the dynamic size.
There's no need to create the files array; simply use the .name field of the directory structure itself; the .name field is a already a char() array so can avoid the cast to/from cellstr entirely.
d = dir('*.mat');
for i=1:length(d)
load d(i).name
% do whatever with that file here...
...
end
  2 Comments
Theresa Marschall
Theresa Marschall on 13 Jun 2018
thank you!
I still get the magical numbers every time I try to use the variable file, but using your way I could bypass the problem
dpb
dpb on 13 Jun 2018
Would need to see that code intact inline with some diagnostics like the output of the cd command or the like to prove it to me.
There's no way it can happen as described with the posted code without something else going on (like a callback function in a gui changing context or such; but even there the variable isn't rewritten unless it's a global and is being updated elsewhere or the like).

Sign in to comment.

More Answers (0)

Categories

Find more on Search Path 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!