Home Sequential import of datafiles according to rule in Matlab
Reply: 2

Sequential import of datafiles according to rule in Matlab

Maria Published in 2018-01-12 08:49:47Z

I have a list of .txt datafiles to import. Suppose they are called like that

file100data.txt file101data.txt ... file109data.txt I want to import them all using readtable.

I tried using the for to specify a vector a = [0:9] through which matlab could loop the readtable command but I cannot make it work.

for a = [0:9]
   T_a_ = readtable('file10_a_data.txt')   

I know I cannot just put _a_ where I want the vector to loop through, so my question is how can I actually do it?

Thank you in advance!

Sheldon Reply to 2018-01-12 09:36:31Z

Here is a solution that should work even if you have missing files in your folder (e.g. you have file100data.txt to file107data.txt, but you are missing file file108data.txt and file109data.txt):

files=dir('file10*data.txt'); %list all data files in your folder
nof=size(files,1); %number of files
for i=1:nof %loop over the number of files
table_index=files(i).name(7) %recover table index from data filename
eval(sprintf('T%s = readtable(files(i).name)', table_index)); %read table

Now, please note that is it generally regarded as poor practice to dynamically name variables in Matlab (see this post for example). You may want to resort to structures or cells to store your data.

am304 Reply to 2018-01-12 09:20:59Z

You need to convert the value of a into a string and combine strings together, like this:

   Tables = struct(); 
   for a = 0:9
       % note: using dynamic structure field names to store the imported tables
       fname = ['file10_' num2str(a) '_data'];
       Tables.(fname) = readtable([fname '.txt']);   
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305579 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO