MATLAB Answers

Table name from input to loop

63 views (last 30 days)
Hi,
I'm loading data from different files in a loop. I want to create a table for each individual data file.
datafiles=recursivedir('PATH','*.txt');
for o = 1:length(datafiles)
%extract date and time from filename
[versn, name, ext] = fileparts(datafiles{o});
filename=datafiles{o};
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false);
fclose(fileID);
T_'name' = table(dataArray{1:end-1}, 'VariableNames', {'Output','Date','Time'});
% I want to create a new table for each loop with the name set from the fileparts.
% Clear temporary variables
clearvars filename delimiter formatSpec fileID dataArray ans;
end
I want to create a table for each loop that has the name like T_test1 and from the fileparts name(1) = 'test1' How do I do this, so I get a table for each loop?
Best regards, Jesper
  6 Comments
Jesper Kamp Jensen
Jesper Kamp Jensen on 29 Jun 2018
Clearly, I do not have enough knowledge nor know-how yet! (But will one ever?)
I thank you very much for your help!! - I completely missed out on what you got the last part! This will do the trick for me - just as you said! :)

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 29 Jun 2018
Edited: Stephen Cobeldick on 29 Jun 2018
Rather than magically defning variable names it is much simpler to use basic MATLAB indexing and a cell array T:
D = 'Path';
S = dir(fullfile(D,'*.txt'));
T = cell(1,numel(S));
for k = 1:numel(S)
[fid,msg] = fopen(fullfile(D,S(k).name));
assert(fid>=3,msg)
C = textscan(fid,...);
fclose(fid);
T{k} = cell2table(C,...);
end

More Answers (0)

Products


Release

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by