Script to load .mat file from a path, calculate a value based on a formula, loop the same until the last file of the folder (could be 1000s) and add the calc'd values in one.

2 views (last 30 days)
I have a folder with thousands of .mat files.
I need some help to write a script that will go in the folder, pick up the first file, choose specific arrays tp build my formula for calculating an X value, then looping the same process again, and adding all the X values from each loop until the last file of the folder.

Answers (1)

Kautuk Raj
Kautuk Raj on 4 Jul 2023
This is a sample script which will help you accomplish what you need:
% Specify the folder containing the .mat files
folder = 'path/to/folder';
% Get a list of all .mat files in the folder
files = dir(fullfile(folder, '*.mat'));
% Initialize an empty array to store the X values
X_all = [];
% Loop through each file in the folder
for i = 1:numel(files)
% Load the current file
file = fullfile(folder, files(i).name);
data = load(file);
% Extract the arrays needed for the X calculation
array1 = data.array1; % replace with actual variable name
array2 = data.array2; % replace with actual variable name
% Calculate the X value from the arrays
X = your_formula(array1, array2); % replace with your actual formula
% Add the X value to the array of all X values
X_all = [X_all; X];
end
% Sum all the X values
X_sum = sum(X_all);

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!