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
댓글 수: 0
채택된 답변
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
newtable = vertcat(x{:}) % vertcat all x once after the loop
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!