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

30 次查看(过去 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,17:45

更多回答(1 个)

Yukthi S
Yukthi S 2024-9-30,18:20
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:

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by