How do I add the filename of where the data came from into a new column in a for loop

4 views (last 30 days)
I am using code very similar to the below code:
I have a folder with different amounts of txt documents with similar names such as 100_2022.txt, 101_2022.txt ect. I take all those txt documents and ultimately am creating one large table that has all the data encased in each document. I am trying to figure out how to add the file name of where that particalar set of data in the table came from into a new coloumn into the table
myFolder = 'C:\users\examples\documents';
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.txt');
myFiles = dir(filePattern);
for k = 1:length(myFiles)
baseFileName = myFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
x{k} = readtable(fullfilename)
newtable = vertcat(x{:});
end

Accepted Answer

Voss
Voss on 9 Dec 2022
Edited: Voss on 9 Dec 2022
myFolder = pwd();%'C:\users\examples\documents';
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.txt');
myFiles = dir(filePattern);
x = cell(1,numel(myFiles)); % pre-allocate cell array x
for k = 1:numel(myFiles)
baseFileName = myFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
x{k} = readtable(fullFileName); % use correct variable name "fullFileName" not "fullfilename"
x{k}.SourceFile = repmat({fullFileName},size(x{k},1),1); % add SourceFile column in table x{k}
end
Now reading /users/mss.system.ejsX5t/sample1.txt Now reading /users/mss.system.ejsX5t/sample2.txt Now reading /users/mss.system.ejsX5t/sample3.txt
newtable = vertcat(x{:}) % vertcat all x once after the loop
newtable = 6×4 table
Var1 Var2 Var3 SourceFile ____ ____ ____ ________________________________________ 1 2 3 {'/users/mss.system.ejsX5t/sample1.txt'} 4 5 6 {'/users/mss.system.ejsX5t/sample1.txt'} 7 8 9 {'/users/mss.system.ejsX5t/sample2.txt'} 10 11 12 {'/users/mss.system.ejsX5t/sample2.txt'} 13 14 15 {'/users/mss.system.ejsX5t/sample2.txt'} 13 14 15 {'/users/mss.system.ejsX5t/sample3.txt'}

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Tags

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!