How do I add the filename of where the data came from into a new column in a for loop
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Voss
le 9 Déc 2022
Modifié(e) : Voss
le 9 Déc 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
newtable = vertcat(x{:}) % vertcat all x once after the loop
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Environment and Settings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!