0

Possible Duplicate:
Loop through files in a folder in matlab

I have a few folders with around 50 csv files in each and I have to read each file and place it in a variable named same as a file but without extension .csv. Files are 2x15000 matrix. Can anyone help? I've searched the Internet, but nothing works for me. Thanks!

Community
  • 1
  • 1
Janja
  • 1
  • 1
  • 1
  • 1
  • 2
    Did you _really_ search the internet? [This question](http://stackoverflow.com/questions/11621846/loop-through-files-in-a-folder-in-matlab) appears first in [Google's search results](https://www.google.com/search?q=looping+through+files+in+a+folder+matlab&rlz=1C1CHEU_enIL452IL452&oq=looping+through+files+in+a+folder+matlab&aqs=chrome.0.57j0l2j62l3.7945&sugexp=chrome,mod=11&sourceid=chrome&ie=UTF-8)... – Eitan T Dec 06 '12 at 12:49
  • @EitanT not exactly a duplicate, I would say. – angainor Dec 06 '12 at 12:54
  • @angainor it's pretty damn close, if you ask me. – Eitan T Dec 06 '12 at 12:55
  • @EitanT Don't think so. How about loading the files into variables named as those files? Nothing there about it. – angainor Dec 06 '12 at 12:56
  • I saw that, but I can't figure out how to put it into a variable named as a file. I'm not even sure if it's posible. I don't want it all to be a giant field, but a 50 different variables – Janja Dec 06 '12 at 12:58
  • Shouldn't one just consider a cell array for storing? If one needs to build up the variable name at run time (eval & co.) to access, she would loose performance (and patience).. – Acorbe Dec 06 '12 at 12:59

2 Answers2

6

Here's another solution:

dd = dir('*.csv');

fileNames = {dd.name}; 

data = cell(numel(fileNames),2);
data(:,1) = regexprep(fileNames, '.csv','');

for ii = 1:numel(fileNames)    
   data{ii,2} = dlmread(fileNames{ii});
end

This will output something like

data = 
    'test1.csv'    [2x15000 double]
    'test2.csv'    [2x15000 double]
    etc.

With this approach, there's really no need to have a zillion variable names flying about. Using cell-arrays in situations like these is generally considered the better way to go; the zillion-variable names approach is "not done".

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
4

I would rather use structures, not variables, to read the individual files:

files=dir('*.csv');
for file = files
    varname = regexp(file.name, '^.\w+', 'match');
    varname = genvarname(varname{:});
    data.(varname) = csvread(file.name);
end

If you want dynamic variables, you will end up using eval, which is not recommended and dangerous.

angainor
  • 11,760
  • 2
  • 36
  • 56