1
votes

I'm trying to read different files (txt) using a datastore and readtable in order to parse them and write them into a .mat file. I'm using ds = datastore('*.txt').Files to get all the file names in a directory, then with a for loop I iterate through all the different files and I save them with different names. However when I import the file in matlab they have all the same table name (dat).

Here's the code:

ds = datastore('*.txt');
fnames = ds.Files;
l = length(fnames);

for i = 1:l
  dat = readtable(fnames{i}, 'Delimiter', '\t');
  dat.Properties.VariableNames(1:2) = {'rpm', 'p_coll'};
  dat = removevars(dat{i},20:width(dat));
  save([fnames{i} '.mat'],'dat');
end

I tried using an array of dat but it didn't work. Any ideas?

1
Why do you want different table names? What added benefit will you get with it? If there are 100 files, you want 100 different table variables? That'd be a very bad thing to do.Sardar Usama

1 Answers

0
votes

As Sardar said there is no point in storing your data in L different variables. If you have to do so, there probably is a bigger problem in your program design. You'd better describe why you need that.

As an alternative, you can load those files in a single cell array:

L = 10;
for ii =1:L
   dat = 2*ii;
   fn = sprintf('dat%d.mat', ii);
   save(fn, 'dat');
end

dats = cell(L, 1);
for ii=1:L
    fn = sprintf('dat%d.mat', ii);
    load(fn);
    dats{ii} = dat;
end

Another option is to lad them in a struct:

dats = struct();
for ii=1:L
    fn = sprintf('dat%d.mat', ii);
    load(fn);
    dats.(sprintf('dat%d', ii)) = dat;
end

I do not see any advantage in this method compared to cell array, but it's kind of funny.

Finally, if you really have a reason to store data in multiple variables, you can use eval:

for ii =1:L
   dat = ii^2;
   eval(sprintf('dat%d=dat;', ii));
   fn = sprintf('dat%d.mat', ii);
   save(fn, sprintf('dat%d', ii));
end

for ii=1:L
    fn = sprintf('dat%d.mat', ii);
    load(fn);
end