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

조회 수: 4 (최근 30일)
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

채택된 답변

Voss
Voss 2022년 12월 9일
편집: Voss 2022년 12월 9일
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'}

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by