Saving output files as input file names while running though a for loop

2 visualizaciones (últimos 30 días)
CAN105
CAN105 el 10 de Feb. de 2023
Respondida: 埃博拉酱 el 13 de Feb. de 2023
I am attempting to run a filtering function on multiple csv files each names a unique date (e.g., '20220527.csv', '20220528.csv', etc.).
Is there a way I can run the function in the for loop and save the output as a csv file taking the input file name (e.g., 'Filt20220527'.csv) for each of the unique files so I each file is different with it's corresponding input filename? I'd also like to have the 3 variable names per file automatically update for each file as they are all different (e.g., 'x532', 'y532', 'Timestamp' and the next file would be 'x533', 'y533', 'Timestamp')
%%%cd ('....my path....')
filePattern = fullfile('*.csv');
thefiles = dir(filePattern);
filename = thefiles.name;
%%% Start looping over files
for k= 1:numel(thefiles)
X= readmatrix(thefiles(k).name);
X_Table = readtable(thefiles(k).name);
TMSP = X_Table(:,[3]);
FilteredSignal = filter(Filter_Butter,X);
T = array2table(FilteredSignal(:,[1:2]));
FiltFinal = [TMSP T]; % Create final filtered data table with timestamp
FiltFinal.Properties.VariableNames = ["x532","y532","Timestamp"]
%%%
%% SAVE
cd ('...\Filtered_Data');
output_name = [FiltFinal, num2str(k) '.csv']; %Saves as FiltFinal1, 2, 3 etc.. but need to save as input name ('Filt20220527.csv' etc...)
writetable(FiltFinal,output_name);
%%%cd ('....my path.....')
end
  3 comentarios
CAN105
CAN105 el 10 de Feb. de 2023
The code is working but I am trying to modify it as I'll be running hundreds of files and rather not have to manually input the variable names each time and change the name of the csv afterwards.
Thanks for the tip!
chrisw23
chrisw23 el 13 de Feb. de 2023
an idea...
for currFile = string(thefiles)
....
output_name = string(FiltFinal) + currFile + ".csv";

Iniciar sesión para comentar.

Respuestas (1)

埃博拉酱
埃博拉酱 el 13 de Feb. de 2023
filenames = struct2table(dir('*.csv')).name;
%%% Start looping over files
for k= 1:numel(filenames)
X= readmatrix(filenames{k});
X_Table = readtable(filenames{k});
TMSP = X_Table(:,3);
FilteredSignal = filter(Filter_Butter,X);
T = array2table(FilteredSignal(:,1:2));
FiltFinal = [TMSP T]; % Create final filtered data table with timestamp
FiltFinal.Properties.VariableNames = ["x"+k,"y"+k,"Timestamp"]
%%%
%% SAVE
writetable(FiltFinal,fullfile('...\Filtered_Data',['Filt',filenames{K}]));
%%%cd ('....my path.....')
end
It's just a simple string concatenation. If your MATLAB doesn't support this operation, it's time for you to update your software.

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by