Read Multiple CSV file from folder, Do calculation, Generate result and save them in a single file

조회 수: 6 (최근 30일)
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.

답변 (1개)

Tejas
Tejas 2024년 12월 27일
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"));

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by