Read Multiple CSV file from folder, Do calculation, Generate result and save them in a single file
Show older comments
Hi Matlabian,
I want to read multiple csv files from a folder for that I am using for loop,
d=dir('*.csv');
for ix=1:length(d)
fn=d(i).name
then I have to take every file separately and need to remove the first column and do the operation accordingly
like;
data = readtable(data) %displays table
x = data{:,1}; %sets x to column 1
y = data{:,2}; %sets y to column 2
A=x+b;
Then need to save every A value corresponding to the file name in a single file.
But my command does not taking the individual file nor saving the dynamic output in a single file.
Answers (1)
Tejas
on 27 Dec 2024
Hello Seum,
The 'dir' function is used to locate CSV files in the current directory. To gather all the CSV file names, make sure to run the script in the directory where these files are located.
To retrieve data from the CSV files and combine it into a single file, follow these steps:
- Retrieve all the CSV file names.
d = dir('*.csv');
results = cell(length(d), 1);
- Go through each file to perform the desired operation. Utilize the 'table' function to store the results.
for ix = 1:length(d)
fn = d(ix).name;
data = readtable(fn);
x = data{:,1};
y = data{:,2};
A = x + y;
columnName = matlab.lang.makeValidName(['Result_' fn]);
results{ix} = table(A, 'VariableNames', {columnName});
end
- Save the results in a single file.
combinedResults = [results{:}];
writetable(combinedResults, 'combined_results.csv');
For a better understanding of the solution, refer to these documentation by running the below commands in MATLAB CLI.
>> web(fullfile(docroot, "matlab/ref/matlab.lang.makevalidname.html"));
>> web(fullfile(docroot, "matlab/ref/table.html"));
Categories
Find more on Workspace Variables and MAT Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!