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 日
  2 件のコメント
Lucas
Lucas 2024 年 9 月 30 日
Thanks Voss!
Voss
Voss 2024 年 9 月 30 日
You're welcome!

サインインしてコメントする。

その他の回答 (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