Run a calculation on multiple different .csv files and export the result

조회 수: 1 (최근 30일)
Lucas
Lucas 2024년 9월 30일
댓글: Voss 2024년 9월 30일
Hello all!
I am new to MATLAB but I am working on performing matrix calculations. I have the calculation code nailed down. The problem is I have 500+ .csv files that I have to read in, perform the calculation, and export each separately.
Is there a way to read in a folder of .csv files, perform my calculation on each, and then export the result of each 500+ calculations to one place?
%so this grabs one single .csv file and performs my calculation%
>> filename='THESISv1-DATA.csv';
M=csvread(filename);
>> S = sum(abs(M(2:end,:)-M(1:end-1,:)),1)

채택된 답변

Voss
Voss 2024년 9월 30일

추가 답변 (1개)

Yukthi S
Yukthi S 2024년 9월 30일
To automate the process of reading multiple .CSV files, performing operations and storing the results in one place, a simple “for” loop can be used.
The below code snippet will help you to get started.
% Define the input and output directories
inputDir = 'path/to/your/csv/files'; % Replace with input directory path
outputDir = 'path/to/save/results'; % Replace with output directory path
% Get a list of all CSV files in the input directory
csvFiles = dir(fullfile(inputDir, '*.csv'));
% Loop through each file
for k = 1:length(csvFiles)
% Construct the full file path
inputFile = fullfile(inputDir, csvFiles(k).name);
% Read the CSV file
M = csvread(inputFile);
% Perform the calculation
S = sum(abs(M(2:end,:) - M(1:end-1,:)), 1);
% Construct the output file path
[~, fileName, ~] = fileparts(csvFiles(k).name);
outputFile = fullfile(outputDir, [fileName, '_result.csv']);
% Save the result to a new CSV file
writematrix(S, outputFile);
end
disp('Processing complete. Results saved.');
As specified in the code, the output .CSV files are saved in “outputDir”
The following MathWorks documentations have more information about the functions used in the code above:
  댓글 수: 1
Lucas
Lucas 2024년 9월 30일
Thank you @Yukthi S. I really appreciate the help :). That makes sense and is easy to follow along.

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

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by