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

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

I do not understand, if the posted code is working or if it has a problem.
Avoid changing the current folder by cd(), but use absolute path names. You started to do so with fullfile('*.csv'). Just include the path here also and the code gets cleaner and more stable.
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!
an idea...
for currFile = string(thefiles)
....
output_name = string(FiltFinal) + currFile + ".csv";

댓글을 달려면 로그인하십시오.

답변 (1개)

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.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2023년 2월 10일

답변:

2023년 2월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by