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

1 visualización (últimos 30 días)
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)

Respuesta aceptada

Voss
Voss el 30 de Sept. de 2024

Más respuestas (1)

Yukthi S
Yukthi S el 30 de Sept. de 2024
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 comentario
Lucas
Lucas el 30 de Sept. de 2024
Thank you @Yukthi S. I really appreciate the help :). That makes sense and is easy to follow along.

Iniciar sesión para comentar.

Productos


Versión

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by