Your attempts are not bad; we usually avoid using EVAL when possible and we don't generate variable names dynamically (I've seen just a few cases over my years with MATLAB where generating dynamically variable names was appropriate).
Here is one approach for reading your data files:
files = dir( '*.txt' ) ;
nFiles = length( files ) ;
names = cell( nFiles, 1 ) ;
data = cell( nFiles, 1 ) ;
for dId = 1 : nFiles
names{dId} = files(dId).name ;
fId = fopen( files(dId).name, 'r' ) ;
cols = textscan( fId, '%f %f', 'headerlines', 1 ) ;
data{dId} = [cols{:}] ;
fclose( fId ) ;
end
You will notice that file names and data are stored in cell arrays, with matching IDs between each name and corresponding data, i.e. data{3} corresponds to names{3}. The line
cols = textscan( fId, '%f %f', 'headerlines', 1 ) ;
creates a cell array of columns. I thought that you would prefer to have a matrix of data, so I implemented a concatenation with [cols{:}], which is what is stored in cell array data. Most often, we want to iterate through data sets and we need to display sometimes a file name that correspond to a given data set. In such case, having the two cell arrays is well adapted, e.g., for display all data sets with the file name as a header, you would do something like
for dId = 1 : length( data )
fprintf( '\nFile: %s\n', names{dId} ) ;
disp( data{dId} ) ;
end
Here you see that the data or file index is numeric. If, for some reason, you really needed to index a data set using a file name, you could use a Java hash table or a MATLAB mapping, or build a mechanism by yourself, e.g.
dId = strcmp( names, 'data2.txt' ) ;
if any( dId )
selection = data{dId} ;
else
error( 'No data found for given file name.' ) ;
end
Best Answer