MATLAB: Devide cell array into unequal length cells based on file name

MATLABmultiple foldersorganize cell arrayorganize dataunequal cell array

With the following code I imported all of the .data files. All .data files of simulation 1 are located in folder 1 and all .data files of simulation 2 are located in folder 2.
%% Loading the data
rhoPart = 2540;
files = dir(fullfile(uigetdir,'\**\*.data*'));
[~,Index] = natsort({files.name});
files = files(Index);
expData = cell(length(files),1);
k = 1;
for i = 1:length(files)
fid = fopen(fullfile(files(i).folder,files(i).name),'r');
%% Reading the data
% Read all the data from the file
dataRead = textscan(fid,'%f %f %f %f %f %f %f %f %f %f %f %f %f %f','HeaderLines',1);
frewind(fid);
% Write headerline N, time, xmin, ymin, zmin, xmax, ymax, zmax
runData{k} = strsplit(fgetl(fid), ' ');
% Write only the x, y, and z components of the particles, particle radius,
% z component+ particle radius and volume of the particle
expData{k} = [dataRead{1}(:,1) dataRead{2}(:,1) dataRead{3}(:,1) dataRead{7}(:,1) dataRead{3}(:,1)+dataRead{7}(:,1) rhoPart*(4/3)*pi*(dataRead{7}(:,1).^3)];
% Write only the vx,vy,vz of the particles and magnitude
velData{k} = [dataRead{4}(:,1) dataRead{5}(:,1) dataRead{6}(:,1) sqrt(dataRead{4}(:,1).^2 + dataRead{5}(:,1).^2 + dataRead{6}(:,1).^2)];
fclose(fid);
k = k + 1;
end
This is the resulting workspace:
Simulation 1 (thus folder 1) contains 2745 .data files and simulation 2 (thus folder 2) contains 2741 files.
Is there a way to organize expData into a 2745×1 cell and 2741×1 cell without having to look up manually how many files each folder contains?

Best Answer

Divide the data based on folder names. Something like this
%% Loading the data
rhoPart = 2540;
files = dir(fullfile(uigetdir,'\**\*.data*'));
[~,Index] = natsort({files.name});
files = files(Index);
folders = {files.folder};
folder_groups = findgroups(folders);
expData = cell(length(files),1);
k = 1;
for i = 1:length(files)
fid = fopen(fullfile(files(i).folder,files(i).name),'r');
%% Reading the data
% Read all the data from the file
dataRead = textscan(fid,'%f %f %f %f %f %f %f %f %f %f %f %f %f %f','HeaderLines',1);
frewind(fid);
% Write headerline N, time, xmin, ymin, zmin, xmax, ymax, zmax
runData{k} = strsplit(fgetl(fid), ' ');
% Write only the x, y, and z components of the particles, particle radius,
% z component+ particle radius and volume of the particle
expData{k} = [dataRead{1}(:,1) dataRead{2}(:,1) dataRead{3}(:,1) dataRead{7}(:,1) dataRead{3}(:,1)+dataRead{7}(:,1) rhoPart*(4/3)*pi*(dataRead{7}(:,1).^3)];
% Write only the vx,vy,vz of the particles and magnitude
velData{k} = [dataRead{4}(:,1) dataRead{5}(:,1) dataRead{6}(:,1) sqrt(dataRead{4}(:,1).^2 + dataRead{5}(:,1).^2 + dataRead{6}(:,1).^2)];
fclose(fid);
k = k + 1;
end
expData_partition = splitapply(@(x) x, expData, folder_groups);