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!