tags:

views:

1104

answers:

1

After asking this question:

how I can read the following files using the for loop: (can the loop ignore the characters in filenames?)

abc-1.TXT cde-2.TXT ser-3.TXT
wsz-4.TXT aqz-5.TXT iop-6.TXT
...

(In fact, I have 500 files)

What do I have to add at the beginning of this loop ??

for i = 1:1:500
nom_fichier = strcat(['MyFile.......' num2str(i) '.TXT']);

I tried the following solution :

Names = dir('MyFile\*.TXT');  

for i = 1:500  
    fn = ['MyFile',filesep,Names{i},'-',num2str(i),'.TXT'];  
    data = load(fn);    
    .....

After running the program, I got the following error:

??? Cell contents reference from a non-cell array object.    

Can you help me to solve this problem. my goal is to read the contents of 500 files.

+4  A: 

You are trying to piece together a solution without thinking about what you are doing.

You need to look and understand what dir returns.

Names = dir('MyFile\*.TXT');

It returns a structure. See that ONE of the fields of this struct is a name field. So try this:

Names(1).name
ans =
  abc-1.TXT

See that it will be the complete name of a file, with no need to build it up. You could now put a loop around this struct,

for i = 1:numel(Names)
  data = load(Names(i).name);

  % do stuff here...
end

If you want the list of names only here as a cell array, then do this next:

Names = {Names.name};

Now, LOOK at what is in this variable. It is a cell array now. Don't just try to use it blindly without thought though. This will be a list of the complete names of every txt file in that directory. You don't need to build up the name at all anymore. Just use load on each file name.

woodchips
Ok, thank you "Woodchips". Could you tell me how I can read them in the order of numbers in filenames
Matlab09
The following program works well:Names = dir('MyFile\*.TXT');for i = 1:500 fn = strcat(['MyFile\' Names(i).name]); ...but the order of the results obtained do not follow the order of numbers in the filenames
Matlab09
Then you need to do a sort of the file names, BEFORE you read the files in.Or if you already know the names of the files except for the numeric modifier, then create them on the fly as has been discussed.
woodchips

related questions