How to open many .mat files and split a box and compile into 1 file.

1 view (last 30 days)
I have a ton of .mat files that need to be opened, split a box column, and compiled into 1 array. I can do this one at a time with the following code. How do I loop the code for an entire folder?
mat = dir('*.mat');
for q = 1:length(mat)
load(mat(q).name);
Calls = splitvars(Calls, 'Box');
Box_4 = Calls{:,5};
end

Answers (1)

Ronit
Ronit on 15 Feb 2024
Hello,
I understand that you are looking to split the ‘box’ column from your dataset and consolidate the extracted information into a unified array. To achieve this, the process involves initializing an empty array that will store the data across multiple iterations.
The code below shows how to do it:
matFiles = dir('*.mat');
allBox_4 = [];
for q = 1:length(matFiles)
load(matFiles(q).name);
% Check if 'Calls' variable exists and has the 'Box' column
if exist('Calls', 'var') && any(strcmp('Box', Calls.Properties.VariableNames))
Calls = splitvars(Calls, 'Box');
Box_4 = Calls{:,5};
% Append the 'Box_4' data to the allBox_4 array (Assuming Box_4 is a column vector)
allBox_4 = [allBox_4; Box_4];
else
warning('Variable "Calls" or column "Box" not found in file: %s', matFiles(q).name);
end
end
save('compiled_Box_4_data.mat', 'allBox_4');
Hope this helps!
Ronit Jain

Tags

Products

Community Treasure Hunt

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

Start Hunting!